views:

78

answers:

1

Nobody seems to have tied together all of the example code in various StackOverflow questions into a good, well-put-together sample of how to handle a photo upload. Here's my start... please help improve it.

Here's our setup:

  • Our file upload control is named $file, e.g. <input type="file" name="<?= $file ?>" />.
  • We want to save the photo to $photosPath, e.g. $photosPath = "/photos/".
  • We want the filename to be $targetFilename . ".jpg", where e.g. $targetFilename could be from a username text field in our upload form.
  • We want to store the resulting file path in $filePath, e.g. for insertion into a database.
  • We want to only accept .jpgs.
  • We want to only accept files of at most $maxSize bytes.
A: 

Here's my shot at it:

// Given: $file, $targetFilename, $photosPath, $maxSize
$filePath = NULL;
if (array_key_exists($_FILES, $file)
    && $_FILES[$file]['size'] != 0
    && $_FILES[$file]['error'] == UPLOAD_ERR_OK)
{
    if ($_FILES[$file]['size'] > $maxSize)
    {
        throw new Exception("The uploaded photo was too large; the maximum size is $maxSize bytes.");
    }

    $imageData = getimagesize($_FILES[$file]['tmp_name']);
    $extension = image_type_to_extension($imageData[2]);
    if ($extension != ".jpg" && $extension != ".jpeg")
    {
        throw new Exception("Only .jpg photos are allowed.");
    }

    $possibleFilePath = $photosPath . $targetFilename . ".jpg";
    if (!move_uploaded_file($_FILES[$file]['tmp_name'],
                            $_SERVER['DOCUMENT_ROOT'] . $possibleFilePath)
    {
        throw new Exception("Could not save the uploaded photo to the server.");
    }

    $filePath = $possibleFilePath;
}
Noah Goodrich