PHP File Upload Tutorial
Uploading files using PHP is a common task in many web applications. In this tutorial, we’ll walk through how to upload files (like images, PDFs, etc.) using HTML and PHP.
Prerequisites
- A basic understanding of HTML and PHP
- A local server environment like XAMPP, WAMP, or MAMP
- A code editor (such as VS Code)
Step 1: Create the Project Folder
Create a folder in your web server’s root directory (e.g., htdocs in XAMPP) named:
📁 file-upload/
Inside it, create two files:
- index.html
- upload.php
Also, create a folder to store uploaded files:
📁 uploads/
Ensure the uploads folder has write permissions.
Step 2: Create the HTML Form (index.html)
This is the form users will use to select and upload a file.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Select file:</label>
<input type="file" name="uploadedFile" required>
<br><br>
<input type="submit" value="Upload File">
</form>
</body>
</html>
Key part: The form must use enctype="multipart/form-data"
to handle file uploads.
Step 3: Handle File Upload with PHP (upload.php)
This script will process the uploaded file and save it to the server.
<?php
// Check if a file has been uploaded
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] == 0) {
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
// Allowed file extensions
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt'];
if (in_array($fileExtension, $allowedExtensions)) {
// Set destination path
$uploadFileDir = './uploads/';
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$destPath = $uploadFileDir . $newFileName;
// Move the file
if (move_uploaded_file($fileTmpPath, $destPath)) {
echo "File uploaded successfully!<br>";
echo "Saved as: " . $newFileName;
} else {
echo "There was an error moving the uploaded file.";
}
} else {
echo "Upload failed. Allowed file types: " . implode(", ", $allowedExtensions);
}
} else {
echo "No file uploaded or upload error.";
}
} else {
echo "Invalid request.";
}
?>
Step 4: Test the Upload
- Start your local server (e.g., Apache via XAMPP).
- Open your browser and go to:
http://localhost/file-upload/index.html - Choose a file and click “Upload File”.
- Check the uploads folder to confirm the file is saved.