【问题标题】:PHP-- filtering uploaded files to imagsPHP--将上传的文件过滤为图像
【发布时间】:2011-03-20 02:14:36
【问题描述】:

如何确保没有 php/html 文件上传到我的服务器?这是我到目前为止的代码,但它不起作用。

<?php 
 $target = "upload/"; 
 $target = $target . basename( $_FILES['uploaded']['name']) ; 
 $ok=1; 

 //This is our size condition 
 if ($uploaded_size > 35000) 
 { 
 echo "Your file is too large.<br>"; 
 $ok=0; 
 } 

 //This is our limit file type condition 
 if ($uploaded_type =="text/php") 
 { 
 echo "No PHP files<br>"; 
 $ok=0; 
 } 

 //Here we check that $ok was not set to 0 by an error 
 if ($ok==0) 
 { 
 Echo "Sorry your file was not uploaded"; 
 } 

 //If everything is ok we try to upload it 
 else 
 { 
 if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
 { 
 echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded and will be revied by moderators.  You will recieve points based on the review."; 
 } 
 else 
 { 
 echo "Sorry, there was a problem uploading your file."; 
 } 
 } 
 ?> 

【问题讨论】:

  • 你从哪里得到$uploaded_size
  • 你在哪里设置$uploaded_type?它的价值是什么?

标签: php file upload


【解决方案1】:

您的代码使用未设置的变量,例如,$uploaded_size,除非您执行类似...

,否则它将为 NULL
$uploaded_size = $_FILES['uploaded']['size'];

此外,检查 MIME 并不能很好地告诉您文件是否包含 PHP。这只是意味着它具有php 扩展名(也就是说,如果您在$_FILES 中检查type)。

为了安全起见,请将上传文件移到 docroot 之外,重命名并删除任何扩展名(以防止 Apache 尝试运行任何恶意文件)。原始文件名和类型可以安全地存储在数据库中,并引用(可能是散列的)新名称。

您可能还需要确保稍后流式传输内容以始终使用 readfile() 回显内容,而不是像 include 之类的东西(即使嵌入在带有 image/gif 的图像中,它也会运行您的 PHP 代码MIME,如果它包含 GIF 标头,则可以说它是一个 GIF)。

【讨论】:

    【解决方案2】:

    查看http://www.php.net/manual/en/function.exif-imagetype.php - 这会检查所有 JPG 开头的某些幻数。此外,正如其他人所指出的,您正在使用未定义的变量...查看文件上传的 PHP 教程(其中还记录了 $_FILE 的内容)。

    http://www.php.net/manual/en/features.file-upload.post-method.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多