linu.us Logo
Linus Benkner

How to upload files with PHP correctly and securely

How to upload files with PHP correctly and securely

How to securely upload files to a server with PHP

Hey Guys,

in this post, I’ll show you how to upload files to your server using HTML and PHP and validate the files. I hope it’s useful for some of you and now happy coding :)

Security information

First of all, the most important thing I want to tell you, the $_FILES variable in PHP (except tmp_name) can be modified. That means, do not check e.g. the filesize with $_FILES['myFile']['size'], because this can be modified by the uploader in case of an attack. In other words, when you validate the upload with this method, attackers can pretend that their file has another file size or type.

So, let’s move on and create our own, secure, file upload.

HTML Setup

Before PHP can handle files, we send them to PHP using a basic HTML form:

<form method="post" action="upload.php" enctype="multipart/form-data">
  <input type="file" name="myFile" />
  <input type="submit" value="Upload" />
</form>

That’s it. Note the action="upload.php", that’s the PHP script handling the upload. And we use the name myFile to identify the file in PHP.


Advertisement

PHP Validation

Now, let’s validate the file in the upload.php file.

First of all, we have to check if there is a file passed to our script. We do this using the $_FILES variable:

if (!isset($_FILES["myFile"])) {
   die("There is no file to upload.");
}

But remember, for security reasons, we can’t get the filesize using $_FILES. When the user uploads the file, PHP stores it temporarily and you can get the path using $_FILES['myFile']['tmp_name']. That’s what we use now to get the real size and type of the file.

$filepath = $_FILES['myFile']['tmp_name'];
$fileSize = filesize($filepath);
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($fileinfo, $filepath);

Now we have the real information, let’s validate the filesize. We don’t want to allow users to upload empty files, so first, we check if the file size is greater than 0:

if ($fileSize === 0) {
   die("The file is empty.");
}

And if anyone can upload files, you might want to set a limit of how large a file can be:

if ($fileSize > 3145728) { // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB))
   die("The file is too large");
}

Great. But you’ll usually only allow specific types to be uploaded, e.g. .png or .jpg for profile images. For more flexibility, let’s create an array with all allowed file types: (Thanks to Gary Marriott and Renorram Brandão for pointing me out, we have to store the extensions for each type here in the array so we can append it later to the filename)

$allowedTypes = [
   'image/png' => 'png',
   'image/jpeg' => 'jpg'
];

You can find a list of MIME-Types here (It’s in german, but there is a great table with all MIME-Types and file extensions).

Now let’s check if the type of the file is allowed:

if(!in_array($filetype, array_keys($allowedTypes))) {
   die("File not allowed.");
}

And we’re done with validating! In the last step, we move the file to our uploads directory (or wherever you want to). For this, I define a variable with my target directory, then grab the current filename and extension and build the new, target file path:

$filename = basename($filepath); // I'm using the original name here, but you can also change the name of the file here
$extension = $allowedTypes[$filetype];
$targetDirectory = __DIR__ . "/uploads"; // __DIR__ is the directory of the current PHP file

$newFilepath = $targetDirectory . "/" . $filename . "." . $extension;

Finally, move the file:

if (!copy($filepath, $newFilepath )) { // Copy the file, returns false if failed
   die("Can't move file.");
}
unlink($filepath); // Delete the temp file

echo "File uploaded successfully :)";

That’s it! Now you have a secure file upload where you can strictly define which files can be uploaded and which not!


Hey 👋 Don't want to miss new articles?

Drop your mail and I'll notify you if I have something new!

* indicates required

Full code

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- Part from this tutorial -->
    <form method="post" action="upload.php" enctype="multipart/form-data">
      <input type="file" name="myFile" />
      <input type="submit" value="Upload" />
    </form>
    <!-- End of part from this tutorial -->
  </body>
</html>

upload.php:

<?php

if (!isset($_FILES["myFile"])) {
    die("There is no file to upload.");
}

$filepath = $_FILES['myFile']['tmp_name'];
$fileSize = filesize($filepath);
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($fileinfo, $filepath);

if ($fileSize === 0) {
    die("The file is empty.");
}

if ($fileSize > 3145728) { // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB))
    die("The file is too large");
}

$allowedTypes = [
   'image/png' => 'png',
   'image/jpeg' => 'jpg'
];

if (!in_array($filetype, array_keys($allowedTypes))) {
    die("File not allowed.");
}

$filename = basename($filepath); // I'm using the original name here, but you can also change the name of the file here
$extension = $allowedTypes[$filetype];
$targetDirectory = __DIR__ . "/uploads"; // __DIR__ is the directory of the current PHP file

$newFilepath = $targetDirectory . "/" . $filename . "." . $extension;

if (!copy($filepath, $newFilepath)) { // Copy the file, returns false if failed
    die("Can't move file.");
}
unlink($filepath); // Delete the temp file

echo "File uploaded successfully :)";

More Articles

Create a WordPress Plugin from Scratch - Full Beginners Guide

Create a WordPress Plugin from Scratch - Full Beginners Guide

Linus Benkner
NeoVim Setup for PHP and NodeJS Development

NeoVim Setup for PHP and NodeJS Development

Linus Benkner
Deploy a SvelteKit-App to DigitalOcean

Deploy a SvelteKit-App to DigitalOcean

Linus Benkner
SQL: The basics and beyond

SQL: The basics and beyond

Linus Benkner
Do you find this content helpful?
Buy Me A Coffee