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. 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:
<?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.
You can also use the $_FILES
array to check if the file is a DOC or PDF file before uploading it. Here is an example of how you can do this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// Check if file is a DOC or PDF file
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if ($fileType != "doc" && $fileType != "pdf") {
echo "Sorry, only DOC and PDF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
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 checks the file extension of the uploaded file and only allows the file to be uploaded if it is a DOC or PDF file. If the file is not a DOC or PDF file, an error message is displayed.