Making this Image Upload Script Secure

I have a form for adding content that I use that allows image uploading that sends the upload through another PHP script. It works great for us, and now I want to setup the same system for my moderators to use, but want to secure the image upload part of the script.

For instance, I want to add functions that:

  1. Return an uploadError if the file name already exists
  2. Reject the upload if not a jpg/gif image.

define("UPLOADDIR", "". $_SERVER['DOCUMENT_ROOT'] ."/folder/images/");

// Detect if it is an AJAX request
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $file = array_shift($_FILES);

if(move_uploaded_file($file['tmp_name'], UPLOADDIR . basename($file['name']))) {
    $file = dirname($_SERVER['PHP_SELF']) . str_replace('./', '/', UPLOADDIR) . $file['name'];
    $file = str_replace("/source/directory/", "", $file);
    $data = array(
        'success' => true,
        'file'    => $file,
    );
} else {
    $error = true;
    $data = array(
        'message' => 'uploadError',
    );
}
} else {
    $data = array(
        'message' => 'uploadNotAjax',
        'formData' => $_POST
    );
}

All feedback appreciated
Ryan

1 Like

I added this:

if ($_FILES["fileToUpload"]["size"] > 220000) {
//too big, stop function
}

$filecheck = explode(".",$file["name"]);
$filec = array_reverse($filecheck);
if($filec[0] != "jpg" && $filec[0] != "png" && $filec[0] != "jpeg" && $filec[0] != "gif" ) {
//no image extension, stop function
}

$target_file = UPLOADDIR .''. $file["name"];
if (file_exists($target_file)) {
//file name already exists, stop function
}  

Seems to do the trick

Cheers!
Ryan

Note that your code also allows png images, where your original comment only wanted to allow jpg or gif formats.

Yeah, decided Iā€™d include that too for testing, but going to remove it. For content images, png use would be crazy.

Cheers
Ryan

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.