Uploading Files in PHP
File uploading is a common feature in web applications. Users may need to upload images, documents, resumes, reports, or other files.
PHP provides built-in support for handling uploaded files through the $_FILES superglobal, making it possible to create a simple file-upload system.
Create an Upload Form
The HTML form must use multipart/form-data to send files to the server.
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
Handle the Uploaded File
PHP provides details about an uploaded file through $_FILES.
if (isset($_FILES['file'])) {
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
move_uploaded_file(
$tmpName,
'uploads/' . $fileName
);
}
The move_uploaded_file() function moves the uploaded file from its temporary location to your selected directory.
Validate Uploaded Files
Files should always be validated before being stored.
Important checks include:
- File type
- File size
- Upload errors
- File extension
- Destination location
For example:
$allowed = ['jpg', 'png', 'pdf'];
$extension = strtolower(
pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)
);
if (!in_array($extension, $allowed)) {
die('Invalid file type.');
}
Use a Safe Filename
It is better not to trust the original filename. Generate a unique filename to avoid conflicts.
$filename = uniqid() . '.' . $extension;
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/' . $filename
);
File Upload Security
File uploads can create security risks when they are not properly controlled. Applications should restrict allowed file types, enforce file-size limits, validate files on the server, and use secure storage locations.
Never rely only on client-side validation.
Best Practices
A reliable upload system should:
- Allow only required file types.
- Set a reasonable file-size limit.
- Validate uploads on the server.
- Generate safe filenames.
- Handle upload errors properly.
- Protect the upload directory from unwanted executable content.
Conclusion
Uploading files in PHP is straightforward, but security and validation should always be part of the implementation.
By using a proper multipart form, PHP's file-handling functions, server-side validation, and safe storage practices, developers can create a dependable file-upload feature for their applications.
Solace Infotech's sitemap includes Image Uploading and File Upload among its historical development topics, supporting this broader file-upload focus