Uploading files in PHP allows users to submit files (such as images, documents, or videos) to a web server. Here’s a step-by-step guide on how to handle file uploads in PHP:
Create an HTML form with the enctype="multipart/form-data"
attribute to allow file uploads.
<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>
In the PHP script specified in the form’s action attribute, handle the file upload process.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["fileToUpload"])) {
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = true; // Check if file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists."; $uploadOk = false;
}
// Check file size (limit to 5MB)
if ($_FILES["fileToUpload"]["size"] > 5 * 1024 * 1024) {
echo "Sorry, your file is too large.";
$uploadOk = false;
}
// Allow only specific 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 = false;
}
// Check if $uploadOk is set to false by an error
if ($uploadOk == false) {
echo "Sorry, your file was not uploaded."; // If everything is ok, try to upload file
} 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.";
}
}
} ?>
By following these steps and best practices, you can securely handle file uploads in PHP and allow users to submit files to your web application.