【问题标题】:PHP File Upload Missing file ExtensionPHP文件上传缺少文件扩展名
【发布时间】:2014-10-16 10:50:03
【问题描述】:

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

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

有人知道为什么会发生这种情况吗?

【问题讨论】:

  • 显示改变前后的功能
  • 我宁愿使用pathinfo($_FILES["vimage1"]["name"], PATHINFO_EXTENSION)来获取扩展名
  • 另外,请提供用于在两个不同功能中上传的表单的代码。

标签: php file-upload


【解决方案1】:

你可以用这个来完成这项工作:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2018-05-10
      • 2020-04-03
      相关资源
      最近更新 更多