-
Hajipur, Bihar, 844101
Uploading files is a common requirement in web applications. Whether you are allowing users to upload profile pictures, documents, or media files, PHP provides a robust and secure way to handle file uploads.
This tutorial explains how to create a file upload form, process uploaded files, validate them, and store them on the server safely.
When a user submits a file through an HTML form:
The file is sent to the server via HTTP POST.
PHP stores it temporarily in a temporary directory.
You can move it to a permanent location using move_uploaded_file()
.
PHP uses the $_FILES
superglobal array to access uploaded files. This array contains information like:
name
– original filename
type
– MIME type of the file
tmp_name
– temporary file path
error
– error code
size
– file size in bytes
First, you need an HTML form with enctype="multipart/form-data"
.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="profile_pic"><br><br>
<input type="submit" value="Upload File" name="submit">
</form>
The enctype
attribute is required for file uploads.
The name
attribute of the input is used to access the file in PHP.
In upload.php
, you can process the uploaded file.
<?php
if(isset($_POST['submit'])) {
$fileName = $_FILES['profile_pic']['name'];
$fileTmp = $_FILES['profile_pic']['tmp_name'];
$uploadDir = "uploads/";
if(move_uploaded_file($fileTmp, $uploadDir . $fileName)) {
echo "File uploaded successfully: " . $fileName;
} else {
echo "Failed to upload file.";
}
}
?>
move_uploaded_file()
moves the file from the temporary directory to a permanent location.
Vrinda can now upload her profile picture and store it in the uploads
folder.
It is important to validate files to prevent security risks.
Check file size
if($_FILES['profile_pic']['size'] > 1048576) { // 1 MB
die("File is too large!");
}
Check file type
$allowedTypes = ['image/jpeg', 'image/png'];
if(!in_array($_FILES['profile_pic']['type'], $allowedTypes)) {
die("Only JPEG or PNG files are allowed.");
}
Rename files to avoid conflicts
$newName = time() . "_" . $_FILES['profile_pic']['name'];
move_uploaded_file($_FILES['profile_pic']['tmp_name'], "uploads/" . $newName);
Using time()
ensures that each file has a unique name.
Ananya can now upload multiple files without overwriting previous ones.
Make sure the uploads
directory exists and has proper permissions.
<?php
if(!is_dir("uploads")) {
mkdir("uploads", 0755, true);
}
?>
0755
gives read/write/execute permissions to the owner and read/execute permissions to others.
This ensures Riya’s uploads are stored safely.
PHP provides error codes in $_FILES['profile_pic']['error']
.
Error Code | Description |
---|---|
0 | No error, file uploaded successfully |
1 | File exceeds upload_max_filesize in php.ini |
2 | File exceeds MAX_FILE_SIZE in HTML form |
3 | File partially uploaded |
4 | No file was uploaded |
6 | Missing temporary folder |
7 | Failed to write file to disk |
8 | File upload stopped by PHP extension |
Example:
<?php
if($_FILES['profile_pic']['error'] !== 0) {
die("Error uploading file. Error code: " . $_FILES['profile_pic']['error']);
}
?>
You can allow multiple files by using multiple
in the form and looping through $_FILES
.
<form action="upload_multiple.php" method="post" enctype="multipart/form-data">
Select files to upload:
<input type="file" name="files[]" multiple><br><br>
<input type="submit" value="Upload Files">
</form>
<?php
if(isset($_FILES['files'])) {
foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
$fileName = $_FILES['files']['name'][$key];
move_uploaded_file($tmpName, "uploads/" . $fileName);
echo "Uploaded: " . $fileName . "<br>";
}
}
?>
Vrinda can now upload several images at once.
Each file is moved to the uploads
directory safely.
Validate file type and size to prevent malicious uploads.
Rename uploaded files to avoid conflicts and security issues.
Store files outside the web root if they are sensitive.
Set correct permissions on upload directories.
Check PHP configuration (upload_max_filesize
and post_max_size
) to allow larger files.
Handle errors gracefully to provide user-friendly messages.
PHP makes file uploading straightforward and flexible. You learned how to:
Create an HTML form for file uploads
Access uploaded files via $_FILES
Move files from temporary to permanent directories using move_uploaded_file()
Validate file size and type
Rename files to prevent overwriting
Handle upload errors
Upload multiple files safely
Using these techniques, Vrinda, Ananya, and Riya can create dynamic applications like profile uploads, content management systems, and media galleries, while keeping the server secure.
Create an HTML form to upload a single file and process it in PHP, saving it in an uploads
folder.
Validate the uploaded file to allow only JPEG and PNG images.
Limit the uploaded file size to 1 MB and display an error if exceeded.
Rename the uploaded file using time()
to avoid overwriting existing files.
Check if the uploads
directory exists and create it if it doesn’t.
Handle file upload errors using $_FILES['file']['error']
and display appropriate messages.
Create a form that allows uploading multiple files and save each file in the uploads
folder.
Display a confirmation message listing all successfully uploaded files.
Restrict users from uploading executable files for security purposes.
Log each uploaded file’s name and upload time into a text file named upload_log.txt
.