我正在使用此代码进行图片上传:
$target_dir = "../uploads/";
$uploadOk=1;
$newname = $target_dir .'file_' . rand(0, 1000000) . '.' . end(explode(".", $_FILES["vimage1"]["name"]));
if (move_uploaded_file($_FILES["vimage1"]["tmp_name"], $newname)) {
echo "The file ". basename( $_FILES["vimage1"]["name"]). " has been uploaded.";
}
else {
echo "Sorry, there was an error uploading your file.";
}
神秘之处在于,我在一个功能中使用了相同的代码,而且一切都很好。
然后我将相同的代码复制到第二个函数,由于某些奇怪的原因,我不断收到上传错误,因为$newname
缺少文件扩展名。
任何人都有任何想法为什么会发生这种情况?
答案 0 :(得分:0)
你可以用这个来完成这个任务:
<?php
function upload($index,$destination,$maxsize=FALSE,$extensions=FALSE)
{
if (!isset($_FILES[$index]) OR $_FILES[$index]['error'] > 0) return FALSE;
if ($maxsize !== FALSE AND $_FILES[$index]['size'] > $maxsize) return FALSE;
// extension
$ext = substr(strrchr($_FILES[$index]['name'],'.'),1);
if ($extensions !== FALSE AND !in_array($ext,$extensions)) return FALSE;
/
return move_uploaded_file($_FILES[$index]['tmp_name'],$destination);
}
//EXEMPLES
$upload1 = upload('icone','uploads/monicone1',15360, array('png','gif','jpg','jpeg') );
$upload2 = upload('mon_fichier','uploads/file112',1048576, FALSE );
if ($upload1) "Successfully uploaded<br />";
if ($upload2) "Failure in uploading!<br />";
?>
答案 1 :(得分:0)
您不能在运行时使用/传递end()
中的数组/变量。你必须首先爆炸文件名然后传递它。像这样的东西。
$proposedExtension = explode(".", $_FILES["vimage1"]["name"]);
$extension = end($imageExtension);
$newname = $target_dir .'file_' . rand(0, 1000000) . '.'.$extension;
echo $newname;
最好使用pathinfo($_FILES["vimage1"]["name"], PATHINFO_EXTENSION)
来获取文件的扩展名。