我正在使用move_uploaded_file上传文件,但是当我上传带有空格的文件时,它不能替换为%20,然后卡在文件名中并带有空格,该如何解决?
这是我的代码:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logoHeader"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["logoHeader"]["tmp_name"]);
if($check === false) {
$error = 'File is not an image.';
include('views/logos/index.php');
break;
}
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
$error = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.';
include('views/logos/index.php');
break;
}
if (move_uploaded_file($_FILES["logoHeader"]["tmp_name"], $target_file)) {
$error = 'Image has been uploaded.';
}
else
{
$error = 'Sorry, there was an error uploading your file.';
include('views/logos/index.php');
break;
}
答案 0 :(得分:0)
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logoHeader"]["name"]);
//new line
$target_file = checkName($target_file);
//end new line
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//your code
并添加checkName函数
function checkName($name){
if(preg_match("`^[-0-9A-Z_\.]+$`i",$name)){
return $name;
}else{
$name = str_replace(' ', '%20', $name);
return $name;
}
但是您仍然无法避免其他“难以理解”的角色。如果文件名包含URL不允许的字符,您将如何给出文件? 例如:ÆÞΔΦÜЩЫž.jpg
尝试查找有关URL slug的更多信息;)