How to Upload Files in PHP - A Step-by-Step Guide
Uploading files is a common feature in web applications. Whether it's images, documents, or other media, PHP provides a straightforward way to handle file uploads. In this step-by-step guide, you'll learn how to implement file uploading in your PHP application.
Step 1: Create an HTML Form
Start by creating an HTML form that allows users to select and upload files.
<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>
Step 2: Create the PHP Script
Create a PHP script (e.g., upload.php) to handle the file upload. In this script, you will validate, process, and move the uploaded file to a secure location.
<?php
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if (isset($_POST["submit"])) {
// Check if the file already exists
if (file_exists($targetFile)) {
echo "Sorry, this file already exists.";
$uploadOk = 0;
}
// Check file size (optional)
if ($_FILES["fileToUpload"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow only specific file formats (e.g., JPEG, PNG)
$allowedFormats = array("jpg", "png", "jpeg");
$fileExtension = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if (!in_array($fileExtension, $allowedFormats)) {
echo "Sorry, only JPG, JPEG, and PNG 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 {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
Step 3: Handle File Upload
In the PHP script, we perform several checks such as ensuring the file doesn't already exist, limiting file size, and allowing only specific file formats. Once validated, we move the file to the desired directory.
Step 4: Display a Success Message
After a successful upload, you can display a success message to the user.
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
Conclusion
You've now learned how to create a simple file upload feature in PHP. Remember to handle file uploads securely, validate user input, and consider file type restrictions to enhance security.