PHP 上传文件 - 仅图像检查

2021-12-24 00:00:00 file-upload image php

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

I have a simple PHP upload script I have started. I am not the best to PHP. Just looking for some suggestions.

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

I want to limit my script to only .JPG, .JPEG, .GIF and .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;

?>

推荐答案

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

Yes, quite easily. But first off, you need some extra bits:

// 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");
}

相关文档:文件上传错误、getimagesize 和 图像常量.

相关文章