How to upload a file securely in PHP?

File upload is risky, because someone can upload a PHP file and run it on your server. Follow these steps to make it safe:

  • Check the upload error with UPLOAD_ERR_OK.
  • Check the real type of the file, not the name or the type sent by the browser.
  • Limit the file size.
  • Give the file a new random name, and never use the original name.
  • Save the file outside the public folder if you can, or at least block PHP execution in the upload folder.
<?php
if ($_FILES["photo"]["error"] !== UPLOAD_ERR_OK) {
    exit("Upload failed.");
}

$allowed = ["image/jpeg" => "jpg", "image/png" => "png"];

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES["photo"]["tmp_name"]);

if (!isset($allowed[$mime])) {
    exit("Only JPG and PNG files are allowed.");
}

if ($_FILES["photo"]["size"] > 2 * 1024 * 1024) {
    exit("File is too big. Maximum 2 MB.");
}

$newName = bin2hex(random_bytes(16)) . "." . $allowed[$mime];
move_uploaded_file($_FILES["photo"]["tmp_name"], "/var/www/uploads/" . $newName);
?>

Learn the basics in PHP File Upload, and how to change the size limit in maximum upload size.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.