PHP上传文件 - 仅图像检查

时间:2012-02-16 15:36:18

标签: php image file-upload

我已经启动了一个简单的PHP上传脚本。我不是最好的PHP。只是寻找一些建议。

我想将我的脚本限制为仅限.JPG,.JPEG,.GIF和.PNG

这可能吗?

<?php
/*
    Temp Uploader
*/

    # vars
    $mx=rand();
    $advid=$_REQUEST["advid"];
    $hash=md5(rand);

    # create our temp dir
    mkdir("./uploads/tempads/".$advid."/".$mx."/".$hash."/", 0777, true);

    # upload dir
    $uploaddir = './uploads/tempads/'.$advid.'/'.$mx.'/'.$hash.'/';
    $file = $uploaddir . basename($_FILES['file']['name']);

    // I was thinking of a large IF STATEMENT HERE ..

    # upload the file
    if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
      $result = 1;
    } else {
      $result = 0;
    }

    sleep(10);
    echo $result;

?>

5 个答案:

答案 0 :(得分:40)

是的,很容易。但首先,您需要一些额外的位:

// never assume the upload succeeded
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
   die("Upload failed with error code " . $_FILES['file']['error']);
}

$info = getimagesize($_FILES['file']['tmp_name']);
if ($info === FALSE) {
   die("Unable to determine image type of uploaded file");
}

if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
   die("Not a gif/jpeg/png");
}

相关文档:file upload errorsgetimagesizeimage constants

答案 1 :(得分:6)

文件路径不一定是检查图像是否真的是图像的最佳方式。我可以使用恶意javascript文件,将其重命名为.jpg扩展名,然后上传它。现在,当您尝试在自己的网站上展示时,我可能刚刚破坏了您的网站。

这是一个验证它真正是一个图像的功能:

<?php
  function isImage($img){
      return (bool)getimagesize($img);
  }
?>

答案 2 :(得分:2)

试试这个:

<?php

function isimage(){
$type=$_FILES['my-image']['type'];     

$extensions=array('image/jpg','image/jpe','image/jpeg','image/jfif','image/png','image/bmp','image/dib','image/gif');
    if(in_array($type, $extensions)){
        return true;
    }
    else
    {
        return false;
    }
}

    if(isimage()){
        //do codes..
    }

?>

答案 3 :(得分:0)

答案 4 :(得分:-1)

if (substr($_FILES["fieldName"]["name"], strlen($_FILES["fieldName"]["name"])-4) == ".jpg")
{
    if(move_uploaded_file($_FILES["fieldName"]["tmp_name"],$path."/".$_FILES['fieldName']['name']))
    {
        echo "image sucessfully uploaded!";
    }
}

同样您也可以检查其他图像格式。

相关问题