File uploading is a common requirement in web applications for tasks such as uploading images, documents, or multimedia files. PHP provides built-in features to handle file uploads securely and efficiently. In this guide, we'll explore how to implement file uploading functionality in PHP, covering both the frontend HTML form and the backend PHP code to handle file uploads.
Frontend HTML Form
First, let's create a simple HTML form to allow users to upload files. We'll use the <form>
element with the enctype
attribute set to "multipart/form-data"
to support file uploads. The form will contain an input field of type file
for selecting the file to upload.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload Form</title>
</head>
<body>
<h2>Upload File</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
Backend PHP Code
Next, let's create the PHP script (upload.php
) to handle the file upload process. This script will receive the uploaded file, perform validation checks, and move the file to a designated directory on the server.
// Check if form is submitted
if(isset($_POST["submit"])) {
$targetDir = "uploads/"; // Directory where uploaded files will be stored
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]); // Path of the uploaded file
$uploadOk = 1; // Flag to indicate if file upload is successful
// Check if file already exists
if(file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (limit to 5MB)
if($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow only certain file formats (e.g., jpg, png, pdf)
$allowedFormats = array("jpg", "png", "pdf");
$fileExtension = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));
if(!in_array($fileExtension, $allowedFormats)) {
echo "Sorry, only JPG, PNG, and PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
// Attempt to upload file
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
Explanation:
HTML Form (index.html
):
- The HTML form contains an input field of type
file
with the name attribute set to"fileToUpload"
. - The form's
enctype
attribute is set to"multipart/form-data"
, which is required for uploading files. - When the form is submitted, it sends the selected file to the server-side PHP script (
upload.php
) for processing.
PHP Script (upload.php
):
- The PHP script checks if the form is submitted and proceeds with file upload processing.
- It defines the target directory (
$targetDir
) where uploaded files will be stored. - The script checks if the file already exists in the target directory and if it's within the allowed size limit.
- It verifies the file format by checking its extension against an array of allowed formats.
- If all checks pass (
$uploadOk == 1
), the script attempts to move the uploaded file from the temporary location to the target directory. - It displays appropriate error or success messages based on the outcome of the upload process.
Practice Excercise Practice now