An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Some of Our Sources
View All SourcesHow to upload files with PHP correctly and securely
If you just want the sourcecode - scroll to the end of the page or click here. But I recommend reading the article to understand why I'm doing things as I do and how it works.
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.
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:
$allowedTypes = [ 'image/png', 'image/jpeg'];
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, $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 = pathinfo($filepath, PATHINFO_EXTENSION);$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 fileecho "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:
<!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:
<?phpif (!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', 'image/jpeg'];if (!in_array($filetype, $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 = pathinfo($filepath, PATHINFO_EXTENSION);$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 fileecho "File uploaded successfully :)";
Original Link: https://dev.to/einlinuus/how-to-upload-files-with-php-correctly-and-securely-1kng
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To