繁体   English   中英

PHP文件上传缺少文件扩展名

[英]PHP File Upload Missing file Extension

我正在使用此代码上传图片:

$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缺少文件扩展名。

任何人都知道为什么会发生这种情况吗?

您可以执行以下操作:

<?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 />";
?>

您不能在运行时在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)来获取文件的扩展名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM