PHP - 文件上传吐出错误

时间:2012-05-01 05:04:42

标签: php file file-upload upload

我正在从我的WebDev类开始进行简单的文件上传练习 - 实际上我们只需要复制代码并将其集成以满足我们的需求。 我试图为我的项目这样做,遗憾的是它会继续回应同样的错误。

<?php

$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg'); 
$max_filesize = 524288; 
$upload_path = 'uploads/'; 

$filename = $_FILES['userfile']['name']; 
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); 
var_export($_FILES, $ext);

 if(!in_array($ext,$allowed_filetypes))
  die('The file you attempted to upload is not allowed.');


 if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
  die('The file you attempted to upload is too large.');


 if(!is_writable($upload_path))
  die('You cannot upload to the specified directory, please CHMOD it to 777.');


 if(move_uploaded_file($_FILES['usrfile']['tmp_name'],$upload_path . $filename))
     echo 'Your file upload was successful, view the file <a href="' . $upload_path .  $filename . '" title="Your File">here</a>';
  else
     echo 'There was an error during the file upload.  Please try again.';

?>

它继续给我'错误的文件类型'错误,包含数组中所有已定义的类型。

<form id='upload' action="uploadfile.php" method="POST" enctype="multipart/form-data">
    <table>
        <tr>
            <td >Choose a File to Upload</td> 
        </tr>
        <tr>
            <td >Select File</td>
            <td  ><input type="file"  name="userfile"></td>
        </tr>
        <tr>
            <td colspan=2 id="sub"><input type="submit" name="submit" value="submit" ></td>
        </tr>
    </Table>
</form>

3 个答案:

答案 0 :(得分:0)

'tmp_name'索引包含临时文件名,而不是文件真正具有的名称。那存储在'name'中。有关信息,请参阅this page

此外,你应该:

  1. 检查'error'索引中的错误。
  2. 使用pathinfo获取扩展程序
  3. 在搜索数组之前将其小写,
  4. 为上传的文件名添加一些随机性,以避免覆盖现有文件。

答案 1 :(得分:0)

$ filename = $ _FILES ['usrfile'] [' name '];

答案 2 :(得分:0)

你可以使用它作为首先你必须始终回显$ _FILES数组然后开始debuging。 从

更改此行
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg'); 

$allowed_filetypes = array('jpg','gif','bmp','png', 'jpeg'); 

更改以下内容

if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)  

if(filesize($_FILES['usrfile']['size']) > $max_filesize)

并删除该行

$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); 

并更改此行

if(!in_array($ext,$allowed_filetypes))  

if(!in_array($_FILES['usrfile']['type'],$allowed_filetypes))