About Lesson
File uploads
File uploading is a very common task in web development — for example, when users upload profile pictures, documents, or resumes. PHP makes file uploads easy using the $_FILES
superglobal.
Steps for File Upload:
- Create an HTML form with
enctype="multipart/form-data"
.- This is required for file uploads.
- Use
input type="file"
.
- Process the uploaded file in PHP.
$_FILES['file']['name']
→ File name$_FILES['file']['tmp_name']
→ Temporary storage path$_FILES['file']['size']
→ File size$_FILES['file']['type']
→ File type- Use
move_uploaded_file()
to store it permanently.
Example: Simple File Upload
HTML Form (upload.html):
HTML
<!DOCTYPE html>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file: <input type="file" name="myfile">
<input type="submit" value="Upload">
</form>
</body>
</html>
PHP Script (upload.php):
PHP
<?php
if (isset($_FILES['myfile'])) {
$target_dir = "uploads/"; // Make sure this folder exists
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) {
echo "The file ". basename($_FILES["myfile"]["name"]). " has been uploaded successfully!";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Explanation:
- The form sends the file data to
upload.php
. - The file is first stored in a temporary location (
tmp_name
). move_uploaded_file()
moves it to the uploads/ folder.- If the folder doesn’t exist, create it manually inside your project.
Basic Validations for Security:
- File size limit:
$_FILES['file']['size']
- Allowed file types (e.g., only images): check
$_FILES['file']['type']
or file extension. - Always sanitize file names before saving.
Output example if you upload photo.jpg
:
The file photo.jpg has been uploaded successfully!