PHP allows users to upload files through a web form. You can process the uploaded files and store them on the server.
To upload a file, you need to create a form with enctype="multipart/form-data"
:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload: <input type="file" name="fileToUpload">
</form>
In the PHP script, use the $_FILES
superglobal to handle the file upload:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Modify the script to check the file type and only allow certain file types (e.g., images or PDFs).
Answers: Use enctype="multipart/form-data"
for file uploads. Access uploaded file data using the $_FILES
superglobal.