How can PHP beginners improve their understanding of uploading files, especially PDF files, on a server?
To improve their understanding of uploading files, especially PDF files, on a server, PHP beginners can start by learning about file handling functions in PHP such as `move_uploaded_file()` and `$_FILES` superglobal array. They should also familiarize themselves with MIME types and file extensions to validate the uploaded files. Additionally, using proper error handling techniques and security measures like file size restrictions and file type checks can help prevent malicious file uploads.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["file"]["name"]);
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if ($fileType != "pdf") {
echo "Only PDF files are allowed.";
} elseif ($_FILES["file"]["size"] > 500000) {
echo "File is too large.";
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
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>