在php中上传文件时我无法上传所有类型的文件,如果文件名之间有任何空间无法下载。请任何人都可以更正此代码
这是我的上传代码
<?php
$target_path = "../mt/sites/default/files/ourfiles/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
$con = mysql_connect("localhost","mt","mt");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}else{
echo "Connected";
}
// Create table
mysql_select_db("mt", $con);
mysql_query("INSERT INTO mt_upload (FileName, FilePath)
VALUES ('".basename( $_FILES['uploadedfile']['name'])."', '".$target_path.basename( $_FILES['uploadedfile']['name'])."')");
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
答案 0 :(得分:1)
对你上传的文件进行一些检查和验证
下面的脚本可以帮助你:
// 5MB maximum file size
$MAXIMUM_FILESIZE = 5 * 1024 * 1024;
// Valid file extensions (images, word, excel, powerpoint)
$rEFileTypes =
"/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|
ppt|pptx){1}$/i";
$dir_base = "/your/file/location/";
$isFile = is_uploaded_file($_FILES['Filedata']['tmp_name']);
if ($isFile) // do we have a file?
{// sanatize file name
// - remove extra spaces/convert to _,
// - remove non 0-9a-Z._- characters,
// - remove leading/trailing spaces
// check if under 5MB,
// check file extension for legal file types
$safe_filename = preg_replace(
array("/\s+/", "/[^-\.\w]+/"),
array("_", ""),
trim($_FILES['Filedata']['name']));
if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE &&
preg_match($rEFileTypes, strrchr($safe_filename, '.')))
{$isMove = move_uploaded_file (
$_FILES['Filedata']['tmp_name'],
$dir_base.$safe_filename);}
}
}
答案 1 :(得分:0)
不确定这是否有效,但请尝试将第2行更改为:
$target_path = $target_path . basename( urldecode ( $_FILES['uploadedfile']['name'] ) );