How can PHP beginners ensure that file attachments are properly handled in their contact forms?
PHP beginners can ensure that file attachments are properly handled in their contact forms by using the PHP `$_FILES` superglobal to access the uploaded file data. They should also ensure that the form has the correct `enctype="multipart/form-data"` attribute set, and move the uploaded file to a designated directory using the `move_uploaded_file()` function.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$file = $_FILES['attachment'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($file["name"]);
if(move_uploaded_file($file["tmp_name"], $target_file)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
?>