Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Uploading files - image only checking

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

I want to limit my script to only .JPG, .JPEG, .GIF and .PNG

Is this possible?

<?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;

?>
like image 776
TheBlackBenzKid Avatar asked Feb 16 '12 15:02

TheBlackBenzKid


1 Answers

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

Relevant docs: file upload errors, getimagesize and image constants.

like image 175
Marc B Avatar answered Nov 15 '22 12:11

Marc B