Upload DOC or PDF using PHP
To upload a DOC or PDF file using PHP, you will need to use the move_uploaded_file function.
To upload a DOC or PDF file using PHP, you will need to use the move_uploaded_file function. This function moves an uploaded file to a new location.
Here is an example of how you can use this function to upload a DOC or PDF file:
Example of uploading DOC or PDF using PHP
<?php
$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.";
}
?>This example assumes that you have a form on your webpage with an input field named fileToUpload. When the form is submitted, the file will be uploaded to the uploads directory on your server. Here is the required HTML form:
<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>You can also use the $_FILES array to validate the file type before uploading it. Here is an example that includes directory creation, error handling, and MIME type checking:
Example of using $_FILES array to upload DOC or PDF using PHP
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
// Create directory if it doesn't exist
if (!is_dir($target_dir)) {
mkdir($target_dir, 0755, true);
}
// Check for upload errors
if ($_FILES["fileToUpload"]["error"] !== UPLOAD_ERR_OK) {
echo "Sorry, there was an error uploading your file.";
exit;
}
// Check MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["fileToUpload"]["tmp_name"]);
finfo_close($finfo);
$allowedMimes = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
if (!in_array($mime, $allowedMimes)) {
echo "Sorry, only DOC and PDF files are allowed.";
exit;
}
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.";
}
?>This example verifies the target directory exists, checks for upload errors, and validates the file using its MIME type before moving it. If the file is not a DOC or PDF file, an error message is displayed.