Write a Code To Upload A File in PHP?
Last Updated :
10 Mar, 2025
PHP makes it easy to upload files in web applications, whether it's for images, documents, or other types of files. With its built-in functions, uploading files to the server becomes a simple task. However, it's important to be cautious when allowing file uploads, as they can pose security risks. Always ensure that you implement proper security measures to prevent any unwanted issues.
Steps to Upload a file in PHP
Step 1: Configure The "php.ini" File
Before we start with the code, ensure that your PHP configuration allows file uploads. To do this, follow these steps:
- Open your php.ini file (usually found in the PHP installation directory).
- Search for file_uploads.
- Make sure it's set to On:
file_uploads = On
Step 2: Create the HTML Form for File Upload
To upload a file, we need an HTML form where users can select a file from their computer. The form must have the following attributes:
- enctype="multipart/form-data": This tells the browser to send the file data as part of the HTTP request.
- method="POST": To submit data securely.
HTML
<html>
<body>
<form action="fileupload.php" method="post" enctype="multipart/form-data">
Directory: <input type="text" name="dirname" id="dirname"><br>
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload"><br>
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
- The form allows users to specify a directory name where the file should be uploaded.
- The <input type="file"> field lets users select a file.
- The form submits data to fileupload.php using the POST method.
Step 3: PHP Script to Handle File Upload
Now let’s look at the PHP script (fileupload.php) that will process the file upload. The script performs several important functions:
- Directory Handling: Verifies if the directory exists or creates a new one if necessary.
- File Extension Validation: Ensures that only valid file types are uploaded.
- File Size Validation: Limits the uploaded file size.
- File Existence Check: Prevents overwriting files with the same name.
1. Directory Handling
First, the script checks if the directory where the file will be uploaded exists. If not, it creates the directory.
PHP
<?php
if(!empty($_POST["dirname"])) {
if(!is_dir($_POST["dirname"])) {
mkdir($_POST["dirname"]);
$uploadOk = 1;
}
} else {
echo "Specify the directory name...";
$uploadOk = 0;
exit;
}
?>
- Check if Directory Exists: Verifies if the specified directory already exists.
- Create Directory if Not Found: Creates the directory using mkdir() if it doesn't exist.
- Error Handling: Stops and shows an error if the directory is not specified.
2. File Extension Validation
Next, the script checks if the uploaded file has a valid extension. The allowed extensions are jpeg, jpg, png, pdf, and gif.
PHP
<?php
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$extensions = array("jpeg", "jpg", "png", "pdf", "gif");
if(in_array($imageFileType, $extensions) === true) {
$uploadOk = 1;
} else {
echo "No file selected or Invalid file extension...";
$uploadOk = 0;
exit;
}
?>
- Get File Extension: Extracts the file extension to check if it's valid.
- Check Against Allowed Extensions: Compares the extension to an array of allowed types (e.g., jpeg, jpg, png).
- Error Handling: Stops and shows an error if the extension is invalid.
3. File Size Validation
The script checks if the uploaded file is within the size limit. In this case, the size limit is set to 10MB.
PHP
<?php
if ($_FILES["fileToUpload"]["size"] > 10000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
exit;
}
?>
- Check File Size: Compares the file size with the set limit (10MB).
- Stop if Too Large: Rejects the file if it exceeds the maximum allowed size.
- Error Handling: Displays an error message if the file is too large.
4. File Existence Check
This ensures that files with the same name do not overwrite existing files in the target directory. It checks whether a file with the same name already exists in the specified directory.
PHP
<?php
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
exit;
}
?>
- Check If File Exists: Verifies if a file with the same name already exists in the target directory.
- Prevent Overwriting: Stops the upload if a file with the same name is found.
- Error Handling: Shows an error message if the file exists.
Complete code for fileupload.php
PHP
<?php
$target_dir = $_POST["dirname"] . "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$extensions = array("jpeg", "jpg", "png", "pdf", "gif");
if (isset($_POST["submit"])) {
// To check whether directory exist or not
if (!empty($_POST["dirname"])) {
if (!is_dir($_POST["dirname"])) {
mkdir($_POST["dirname"]);
$uploadOk = 1;
}
} else {
echo "Specify the directory name...";
$uploadOk = 0;
exit;
}
// To check extensions are correct or not
if (in_array($imageFileType, $extensions) === true) {
$uploadOk = 1;
} else {
echo "No file selected or Invalid file extension...";
$uploadOk = 0;
exit;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
exit;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 10000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
exit;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
// If everything is ok, try to upload file
if (
move_uploaded_file($_FILES["fileToUpload"]
["tmp_name"], $target_file)
) {
echo "The file " . $_FILES["fileToUpload"]
["name"] . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Output
write the directory name and select the file
after uploading the file Optimizing File Upload Performance
- Chunked Uploads: For large files, consider breaking the file into smaller chunks and uploading them sequentially. This reduces server load and increases reliability in case of connection interruptions.
- Image Optimization: Before uploading, compress images to reduce file size without compromising quality. This can be done client-side using JavaScript or server-side with PHP libraries like GD or ImageMagick.
- Use Asynchronous Uploading: Leverage AJAX or XMLHttpRequest for asynchronous file uploads to avoid blocking the main thread and improve user experience.
Best Practices
- File Validation: Always validate file types, sizes, and extensions to prevent malicious files from being uploaded.
- Security: Sanitize filenames and store files in a directory with restricted access to protect the server.
- Efficient Handling: Use chunked uploads for large files, optimize images for size, and ensure real-time feedback during the upload process.
- Database Integration: Optionally, store file metadata in a database for better tracking and management.
- Error Handling: Implement clear error messages and checks for better user experience during the upload process.
Conclusion
File upload functionality is an essential feature in web applications. By ensuring proper validation, optimizing file sizes, and following best practices, we can improve both the performance and security of your file upload process. Implementing chunked uploads, image optimization, and secure storage will not only enhance user experience but also prevent potential server issue.
Similar Reads
How to upload a file in PHP ?
In this article, we will learn how to upload a file using PHP. Let us first understand some basic configurations. Approach: In your "php.ini" file, search for the "file_uploads" parameter and set it to "On" as mentioned below. file_uploads = On In the "index.html" file, the enctype must be multipart
3 min read
How to access error code associated with file upload in PHP ?
Error in PHP occurs when we do not deal with the cases accordingly. There are many errors that occur during the file upload. The errors are as follows The size of the file is greater than the expected sizeThe extension is not correct or we can say the file type is not matching according to the cond
3 min read
How to write Into a File in PHP ?
In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file
2 min read
How to access actual name of uploaded file in PHP ?
In PHP, we can access the actual name of the file which we are uploading by keyword $_FILES["file"]["name"]. The $_FILES is the by default keyword in PHP to access the details of files that we uploaded.The file refers to the name which is defined in the "index.html" form in the input of the file.The
2 min read
PHP $_FILES Array (HTTP File Upload variables)
How does the PHP file handle know some basic information like file-name, file-size, type of the file and a few attributes about the file that has been selected to be uploaded? Let's have a look at what is playing behind the scene. $_FILES is a two-dimensional associative global array of items that a
3 min read
How to Append Data to a File in PHP?
Appending data to a file is a common operation in PHP when you want to add new information without overwriting the existing content. This can be particularly useful for logging, saving user activity, or adding records incrementally. We will explore different approaches to appending data to a file in
2 min read
How to convert an array to CSV file in PHP ?
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the leng
2 min read
Upload File With Selenium in Python
Uploading files using Selenium in Python allows developers to automate the process of interacting with file input elements on web pages. Leveraging the Selenium WebDriver, this tutorial guides users through the steps of locating file input elements, providing the file path for upload, and handling t
2 min read
How to add file uploads function to a webpage in HTML ?
Adding a file upload function to a webpage in HTML allows users to select and upload files from their device to a server. This is achieved using the <input type="file"> element within a form, enabling file selection and submission for processing or storage.Table of ContentUsing Single File Upl
2 min read
Perl | File Upload in CGI
Perl is general-purpose programming language, specially designed for text manipulation and in present time used for various task including system administration, web development, network programming, GUI development, and in other more area. In Perl, CGI(Common Gateway Interface) is a protocol for ex
3 min read