PHP安全图像上传 - 附加代码?

时间:2015-09-01 18:15:09

标签: php mysql image

这是我将图像文件上传到php / mysql服务器的代码。我已经阅读了类似的帖子和教程,但大多数人都说他们不完整。

这是否足够安全或者还会缺少什么?

if(isset($_FILES["file"]) && $_FILES["file"]['error'] == 0)
{
$file = $_FILES["file"];

    $file = $_FILES["file"]['name'];
    $file_type = $_FILES["file"]['type'];
    $file = strtolower($file);
    $file_type = strtolower($file_type);

    if(is_array($_FILES["file"]['error'])){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
        die('Erro: Only one file accepted');
    }

    $max_file_size = 2097152;
    if($_FILES['file']['size'] >= $max_file_size || $_FILES['file']['size'] == 0){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
        die('Erro: file size exceeded (2mb)');
    }

    /* check if contain php */
    $pos = strpos($file, 'php');
    if(!($pos === false)) {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('Error: image has php script');
    }

/* finfo */ 
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['file']['tmp_name']);
$allowed2 = array('jpg'=>'image/jpeg', 'png'=>'image/png', 'jpeg'=>'image/jpeg');
$ext = array_search($mime, $allowed2, true);

    if(false === $ext){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('FileInfo: Extension not allowed');     
    }

    /* get file extension */
    $file_ext = strrchr($file, '.');

    /* check if it is allowed */
    $allowed = array(".jpg",".jpeg",".png");
    if (!(in_array($file_ext, $allowed))) {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('Extension not allowed');
    }

    /* check upload type */
    $pos = strpos($file_type,'image');
    if($pos === false) {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('error 1: Mime type not valid');
    }

    $imageinfo = getimagesize($_FILES['file']['tmp_name']);
    if($imageinfo['mime'] != 'image/jpeg'&& $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('error 2: size mime type not valid');
    }

    //check double file type (image with comment)
    if(substr_count($file_type, '/')>1){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
        die('error 3: double type');
    }

    /* upload to upload direcory */ 
    $uploaddir = 'up_files/';

    if (file_exists($uploaddir)) {  
    } else {  
mkdir( $uploaddir, 0777);  
}  
/* change the image name */
$uploadfile = $uploaddir . md5(basename($_FILES['file']['name'])).$file_ext;

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    echo "";
} else {
    echo "Error moving image file";
    echo '<a href="cad_p.php">Try again</a>';
}

$name = $_POST['name'];

if ($insert_stmt = $mysqli->prepare("INSERT INTO products (name, file) VALUES (?, ?)")) {$insert_stmt->bind_param('ss', $name, $uploadfile);

if (! $insert_stmt->execute()) {
    echo '<div class="register_success">';
    echo "Could not insert...";
    echo '</div>';
}else{
    echo '<div class="register_success">';
    echo "Product Insert success...";
    echo '</div>'; 
}

}
}
else
{
echo '<a href="cad_p.php">Tente novamente</a>';
echo "<br/>";   
echo "<br/>";   
die('No image file selected');  
}

1 个答案:

答案 0 :(得分:1)

After reading comments in the PHP manual I found this from a user named sparticvs:

"A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type. I recommend using finfo_open (http://www.php.net/manual/en/function.finfo-open.php) to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems)."

Go here and scroll down to see his comment: http://php.net/manual/en/reserved.variables.files.php

If you are intent on using that solution however here are some pointers:

Use strip_tag() this is on the off chance that someone somehow manages to get some HTML or PHP tags into your code. Read more here: http://php.net/manual/en/function.strip-tags.php

$name = $_POST['name']; This seems dangerous. You're not doing any checks at all. I would recommend strip_tags again and type validation.

EDIT: I'll add my teachers notes to this answer:

  • Make sure it's not a fake file by using getimagesize() this will return false upon failure. (Or something similiar) Limit the file size.
  • Always check the extension and only allow the ones you want to.
  • Change the name of the file or clear the name using strip_tags/htmlentities.
  • Don't ever save the file directly in your database.
  • If the file name has a space in it, encode it properly.