Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
PHP makes it easy to upload both single and multiple files with just a few lines of code.
The file upload feature in PHP supports uploading text and binary files seamlessly. Additionally, PHP provides robust control over the upload process using authentication and file handling functions, ensuring secure and efficient file management.
In this article, we’ll guide you through the process of uploading files using PHP, from configuring the PHP environment to writing the necessary code for uploading and validating files. You will learn how to ensure security and proper functionality when uploading files to your web server.
Configure The "php.ini" File
The first step in allowing file uploads in PHP is to configure the php.ini file, which is the configuration file for PHP. This file controls many important settings for PHP, including those related to file uploads.
To enable file uploads, make sure the following settings are correct in your php.ini file:
file_uploads: This setting must be enabled. If it is set to "Off", file uploads are disabled.
upload_max_filesize: This defines the maximum allowed size for uploaded files.
post_max_size: This defines the maximum size of data that can be sent to the server, which should be larger than the file size you allow for uploads.
max_file_uploads: This defines the maximum number of files that can be uploaded simultaneously.
max_file_uploads: Allows uploading a maximum of 20 files in a single request.
After making these changes, restart your web server for the changes to take effect.
PHP $_FILES
In PHP, the $_FILES superglobal is used to handle file uploads. It is an associative array that contains information about the uploaded files, such as the file name, type, size, & temporary location on the server. When a file is uploaded via an HTML form with the enctype attribute set to "multipart/form-data", the file data is available in the $_FILES array.
The $_FILES array has a specific structure. For each uploaded file, it contains a sub-array with the following elements:
"name": The original name of the uploaded file
"type": The MIME type of the uploaded file
"tmp_name": The temporary name of the file on the server
"error": An error code associated with the file upload
"size": The size of the uploaded file in bytes
By accessing these elements, you can retrieve information about the uploaded file & perform necessary validations & operations.
Let’s take an example of how to access the uploaded file information:
In this code snippet, we first check if the 'uploadedFile' key exists in the $_FILES array using the isset() function. If it does, we can access the various elements of the uploaded file using the respective keys.
move_uploaded_file() function
The move_uploaded_file() function in PHP is used to move an uploaded file from its temporary location to a desired destination on the server. It takes two parameters: the source path (the temporary location of the uploaded file) & the destination path (where you want to move the file).
The basic syntax of the move_uploaded_file() function is:
The function returns true if the file is successfully moved, or false if the move operation fails.
When a file is uploaded, PHP stores it in a temporary directory on the server. The move_uploaded_file() function allows you to move the file from this temporary location to a permanent location of your choice. It is important to note that the destination directory must have the necessary permissions for PHP to write files to it.
Let’s discuss an example of how to use the move_uploaded_file() function:
if (isset($_FILES['uploadedFile'])) {
$fileTmpName = $_FILES['uploadedFile']['tmp_name'];
$destinationPath = 'uploads/' . $_FILES['uploadedFile']['name'];
if (move_uploaded_file($fileTmpName, $destinationPath)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading the file.';
}
}
In this code snippet, we first check if the 'uploadedFile' key exists in the $_FILES array. If it does, we retrieve the temporary name of the uploaded file using $_FILES['uploadedFile']['tmp_name']. We then specify the destination path where we want to move the file. In this example, we are moving the file to a directory named 'uploads' with the original file name.
Finally, we use the move_uploaded_file() function to move the file from its temporary location to the specified destination path. If the move operation is successful, it will return true, & we echo a success message. If the move fails, we echo an error message.
Create The HTML Form
Once PHP is configured to handle file uploads, the next step is creating an HTML form that allows users to select a file and upload it.
The form element uses the POST method to send data to the server.
The enctype="multipart/form-data" attribute ensures that the file is properly encoded before being sent.
The input type="file" creates a file input field, allowing users to select a file from their computer.
When the form is submitted, it sends the file to upload.php, which we will create next.
Create The Upload File PHP Script
Now, let’s create the PHP script that handles the file upload. The script will process the file uploaded via the form, move it to a specific directory, and handle basic error checking.
<?php
if(isset($_POST['submit'])){
$target_dir = "uploads/"; // directory to store uploaded files
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if file size is too large
if ($_FILES["fileToUpload"]["size"] > 500000) { // 500 KB limit
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
You can also try this code with Online PHP Compiler
File size: Restricts file uploads to files smaller than 500 KB.
File type: Only allows image files (JPG, PNG, JPEG, GIF).
Check if File Already Exists
In the script above, we already check if the file exists using the file_exists() function. If a file with the same name already exists in the upload directory, the upload is aborted, and an error message is shown. This prevents overwriting of files with the same name.
Limit File Size
To limit the file size, we use the $_FILES["fileToUpload"]["size"] value, which contains the size of the uploaded file in bytes. In our example, the size limit is set to 500 KB. If the uploaded file exceeds this size, an error message is displayed.
You can change the limit by modifying this check:
if ($_FILES["fileToUpload"]["size"] > 500000) { // 500 KB limit
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type
To limit the types of files that can be uploaded, we use the file’s extension. We check the file type against a list of allowed extensions (JPG, PNG, JPEG, GIF).
You can add or remove file extensions as per your requirements.
Complete Upload File PHP Script
Combining all the elements, here’s the complete PHP file upload script:
<?php
if(isset($_POST['submit'])){
$target_dir = "uploads/"; // directory to store uploaded files
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if file size is too large
if ($_FILES["fileToUpload"]["size"] > 500000) { // 500 KB limit
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
Frequently Asked Questions
How do I upload multiple files at once in PHP?
To upload multiple files, modify the HTML form by adding multiple to the file input tag. Then, loop through $_FILES in PHP to process each file.
What happens if I don’t check for file type and size?
Without these checks, users could upload unwanted files, like large files or malicious files that could harm your server or application.
How can I change the maximum file size allowed for uploads?
Change the upload_max_filesize and post_max_size values in the php.ini file to adjust the maximum file size.
Conclusion
In this article, we've learned how to implement a basic file upload feature using PHP. We've configured the PHP environment, created an HTML form to select files, and built a PHP script to process and validate the uploads. You should now be able to handle file uploads securely, limit file size and types, and check for errors during the upload process.