How can a PHP beginner successfully implement a file upload feature on a form?
To implement a file upload feature on a form in PHP, a beginner can use the $_FILES superglobal to handle the uploaded file. The form should have the enctype attribute set to "multipart/form-data" to allow file uploads. The PHP script should move the uploaded file from the temporary directory to a desired location on the server.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
$file = $_FILES["file"];
$uploadDir = "uploads/";
$uploadFile = $uploadDir . basename($file["name"]);
if (move_uploaded_file($file["tmp_name"], $uploadFile)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>