How to upload files with PHP correctly and securely
Tags: php, html, beginners, tutorial
Published: 2021-04-17 18:44:32

<small>*If you just want the sourcecode - scroll to the end of the page or click [here](#full-code). But I recommend reading the article to understand why I'm doing things as I do and how it works.*</small>

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.

As you can see, there is a lot we need to take care of. Maybe it's worth considering to use an already existing service. With [Uploadcare](https://uploadcare.com/) you can upload and manage files quickly and easily via their [PHP integration](https://uploadcare.com/docs/integrations/php/).

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:

```html
<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.

## 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:

```php
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.

```php
$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:

```php
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:

```php
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](https://dev.to/ramriot) and [Renorram Brandão](https://dev.to/renorram) 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)

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

You can find a list of MIME-Types [here](https://wiki.selfhtml.org/wiki/MIME-Type/%C3%9Cbersicht) (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:

```php
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:

```php
$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: 
```php
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!

## Full code

index.html:
```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
<?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 :)";
```