Uploading PDFs to a directory PHP - php

I'm uploading PDFs to a directory and my script works fine for one directory but I'm having troubles coming up with a way to write the script efficiently when I have more then one directory to upload PDFs on a page. I know of a few ways I can do it, like write another function like below but there must be a better way so I dont have to write out the whole script for every directory I want to upload PDFs to. Code below.
if(is_post_request()) {
$targetdirectory = "../../pathofdirectory/pdf/";
$targetdirectory = $targetdirectory . basename( $_FILES['file']['name']) ;
$file_type=$_FILES['file']['type'];
if ($file_type=="application/pdf") {
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetdirectory))
{
$message = "The file ". basename( $_FILES['file']['name']). " is uploaded";
}
else {
$message = "Problem uploading file";
}
}
else {
$message = "You may only upload PDFs.<br>";
}
}
And of course the simple form
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<input class="button common" type="submit" value="Submit" />
</form>
Thanks in advance for any suggestions.

If you're okay with allowing users choosing which directory to upload to, you can give them the option.
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<select name="folderOption">
<option value="1">First Folder</option>
<option value="2">Second Folder</option>
<option value="3">Third Folder</option>
</select>
<input class="button common" type="submit" value="Submit" />
</form>
Obviously, you would need to validate server-side for bad data.
if (is_post_request()) {
$targetdirectory = "../../pathofdirectory/pdf/";
$targetdirectory = $targetdirectory . basename( $_FILES['file']['name']) ;
$file_type = $_FILES['file']['type'];
$folderOption = $_POST['folderOption'];
if ($folderOption == 1 || $folderOption == 2 || $folderOption == 3) {
switch ($folderOption) {
case 1:
$targetdirectory = "../../pathofdirectory/pdf/";
break;
case 2:
$targetdirectory = "../../pathofdirectory2/pdf/";
break;
case 3:
$targetdirectory = "../../pathofdirectory3/pdf/";
break;
default:
$targetdirectory = "../../pathofdirectory/pdf/";
}
if ($file_type == "application/pdf") {
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetdirectory)) {
$message = "The file ". basename( $_FILES['file']['name']). " is uploaded";
} else {
$message = "Problem uploading file";
}
} else {
$message = "You may only upload PDFs.<br>";
}
} else {
$message = "Bad data received for directory choice.<br>";
}
}

Related

uploading video file not working

I want to upload video files in php for that i am using following code
PHP
$newUploadDir = "c://video";
$idx = "file";
if (isset($_FILES[$idx]) && is_array($_FILES[$idx])) {
echo "file set";
foreach ($_FILES[$idx]["error"] as $key => $error) {
echo "loop";
if ($error == UPLOAD_ERR_OK) {
echo "<br/>dd2";
$tmp_name = $_FILES[$idx]["tmp_name"][$key];
$name = $_FILES[$idx]["name"][$key];
$ext1 = explode(".", $name);
$extension = end($ext1);
$newfilename = "test".".".$extension;
$video_types = array('mp4', 'avi','webm');
if (in_array($extension, $video_types)) {
if (move_uploaded_file($tmp_name, $newUploadDir.$newfilename)) {
echo "uploaded to folder";
} else {
echo "Not uploaded to folder";
}
}
} else {
echo "not uploaded $error";
}
}
}
echo "ok";
HTML
<form action="http://localhost/fileupload/video.php" enctype="multipart/form-data" method="post">
<input id="file1" name="file[]" type="file"/>
<input name="userId" type="text" value="2"/>
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
Output
file setloopnot uploaded 1ok
Video file is not uploading. How to resolve this?
Actually, if you try to upload very large (video) files, probably the upload file size limit will not let you do that. Instead of regular file upload, there are other possibities. For the begining, look at this, this or this.
An other aproach would be to use third party services like Amazon S3, Microsoft Azure, etc.

How can I get the picture I uploaded to my sever link to my website

I have created a basic car sales website. I have used the following PHP code to upload my image
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
So the file is being uploaded to the server and that is great (took me ages to get it to work), I am using phpliteadmin as my database manager and I have a field called car_image_url, this is where i paste the url to the image on the server, however I have added a page on the site where users can upload an image themselves, so my question is how can I get this to work.
I am using the following to convert the url to display an image.
echo "<td id='img'><img src=\"". $row["car_image_url"] . "\" /></td>";
However uploading the file is a different story, what code do I use on my website to get the uploaded file to link to the image url.
Here is my PHP code that makes a new car on the main site:
<?php
try {
# Connect to SQLite database
$dbh = new PDO("sqlite:../Car_Sales_Network");
$make = $_POST['Make'];
$model = $_POST['Model'];
$badge = $_POST['Badge'];
$price = $_POST['Price'];
$trans = $_POST['Transmission'];
$ppl = $_POST['P_Plate_Legal'];
$sth = $dbh->prepare('INSERT INTO Cars_On_Network
("car_make","car_model","car_badge","price","trans","P_Plate_Legal")
VALUES
(?, ?, ?, ?, ?, ?)');
$sth->execute(array($make, $model, $badge, $price, $trans, $ppl));
$id = $dbh->lastInsertId();
//header("Location: ../Carsales_Network.php");
}
catch(PDOException $e) {
echo $e->getMessage();
}
$target_folder = "Cars_Photos/";
$target_path = $target_folder . basename( $_FILES['fileToUpload']['name'] );
//echo $target_path . '<br><br><br>';
//print_r($_FILES);
print($_FILES['fileToUpload']['tmp_name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>New Vehicle</title>
<link type="text/css" rel="stylesheet" href="New_Car_Form.css"/>
</head>
<body>
<div id="main">
<form action="Insert_Car.php" method="post" enctype="multipart/form-data">
Make:<br>
<input type="text" name="Make">
<br>
Model:<br>
<input type="text" name="Model">
<br><br>
Badge:<br>
<input type="text" name="Badge">
<br>
Price:<br>
<input type="text" name="Price">
<br>
Transmission: <br>
<input type="radio" name="Transmission" value="Manual" checked>Manual
<br>
<input type="radio" name="Transmission" value="Auto">Automatic
<br><br>
P Plate Legal: <br>
<select name="P_Plate_Legal">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Choose a Picture: <br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<br>
<br>
<input class="submit" type="submit" value="Submit">
<br>
Let's go back!
<br>
</div>
</body>
</html>
</form>
</body>
</html>
I am sure it is a similar process however I just can't think of how to do it.
Cheers.
it seems to me like youre having trouble with the upload script.
Here is a way that comes in handy (It creates an unique name for all images)
Crate your sql within the WRITE TO DATABASE comment i made:
if(isset($_FILES['fileToUpload'])){
$File = $_FILES['fileToUpload'];
//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];
//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));
//Allowed files:
$Allowed = array('jpg', 'png', 'jpeg', 'gif');
//Check if file is allowed:
if(in_array($FileExt, $Allowed)){
//Does it return an error?
if($FileError==0){
//Create new filename:
$NewName = uniqid('', true) . '.' . $FileExt;
//Destination
$UploadDestination = $_SERVER['DOCUMENT_ROOT'] . '/Cars_Photos/' . $NewName;
//Move file to location:
if(move_uploaded_file($TmpLocation, $UploadDestination)){
//Filename = $NewName
//WRITE TO DATABASE:
//encode url:
$Image = urlencode($UploadDestination);
//Redirect:
header("Location: /complete.php?image=$Image&cat=Cars");
}
//File didnt upload:
else{
echo "File didnt upload...";
}
}
//An error occured
else{
echo "An error occured while uploading...";
}
}
//Filetype not allowed
else{
echo "Sorry, the file you tried to upload is not allowed.";
}
}
Complete.php:
<?php
//Your file is here:
echo urldecode($_GET['image']);

PHP uploading form problems

Im having problems with my uploading form using php I have created pages like this in the past but for some reason this one seems to be playing up I'm hoping i have just missed something so simple. Im trying to create and upload form to upload Wav, rar, zip and txt files and returning error on everything else.
If i try and upload a file which is not related to these it shows an error but if i try to upload a wav or a zip file it doesn't work i don't get any kind of error report but if i was to upload a .txt file it seems to work fine.
my html code is;
<form action="<?php echo $site_url; ?>upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="upload" id="upload" value="upload" />
<label for="invoice"><strong>Select Invoice Number</strong></label>
<select name="invoice" <?php if (array_key_exists('invoice', $add_product_errors)) echo ' class="error"'; ?>>
<?php while($row = mysqli_fetch_array($r)){ ?>
<option value="<?php echo $row[0] ; ?>"
<?php if (isset($_POST['invoice']) && ($_POST['invoice'] == $row[0]) ) echo ' selected="selected"';
echo ">" .$row[0]. "</option>\n"; ?>
<?php } ?>
</select><?php if (array_key_exists('invoice', $add_product_errors)) echo ' <span class="error">' .$add_product_errors['invoice']. '</span>'; ?>
<label for="track"><strong>Upload File</strong></label>
<input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
<input type="file" name="song" id="song" <?php if (array_key_exists('song', $add_product_errors)){ echo " class=\"error\" /> <span class=\"error\">" .$add_product_errors['song']. "</span>"; }else{ echo ' />'; if (isset($_SESSION['song'])){ echo " CURRENTLY '{$_SESSION['song']['file_name']}'"; } } ?>
<input type="submit" name="upload_files" id="upload_files" value="Upload Files" />
</form>
and my php script;
if(isset( $_POST['upload'])){
if(is_uploaded_file($_FILES['song']['tmp_name']) && ($_FILES['song']['error'] == UPLOAD_ERR_OK)){
$file = $_FILES['song'];
$size = ROUND($file['size']/1024);
if($size > 5120000){
$add_product_errors['song'] = 'The File Size is too Big';
}// END FILE SIZE
$allowed_mime = array('audio/wav', 'audio/x-wav', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip', 'text/plain');
$allowed_extensions = array('.wav', '.zip', '.rar', '.txt');
$ext = substr($file['name'], -4);
if((!in_array($file['type'], $allowed_mime))
|| (!in_array($ext, $allowed_extensions))
){
$add_product_errors['song'] = "We Only accept .wav and .zip files please do not send .mp3 files";
}// END IF WRONG EXT
if (!array_key_exists('song', $add_product_errors)){
$dest = "clients/" . $username[0] . "/" . $_POST['invoice'] . "/" . $file['name'];
if(move_uploaded_file($file['tmp_name'], $dest)){
// $_SESSION['image']['new_name'] = $new_name;
$_SESSION['song']['file_name'] = $file['name'];
$add_product['text'] = "Files has successfully been moved\n";
}else{
trigger_error('the file could not be moved.');
unlink($file['tmp_name']);
}// END if file is moved
}// END if file can be moved
}elseif (!isset($_SESSION['song'])){
switch ($_FILES['song']['error']){
case 1:
case 2:
$add_product_errors['song'] = "File is too big 5GB Max";
break;
case 3:
$add_product_errors['song'] = "the file was partially uploaded";
break;
case 6:
case 7:
case 8:
$add_product_errors['song'] = "Couldn't upload due to a system error";
break;
case 4:
default:
$add_product_errors['song'] = "No file was uploaded";
break;
}//END OF SWITCH
}
if(empty($add_product_errors)){
echo 'yes';
$body = $username[0] . " has uploaded files in to " . $_POST['invoice'] . " Ready to start downloading and working on";
//mail($site_email, 'file has been loaded',$body,'from:' .$site_email);
//$_POST = array();
//$files = array();
unset($file,$_SESSION['song']);
}
}//END IF $_POST UPLOAD
any help would be so much appreciated thank you
Try removing the check for mime types and see what it gives first

php upload works only for windows, not for linux

I have a weird problem, I have a php upload code that I have implemented long ago, today I try to reuse it but it didn't work, the surprise was big when I started my Windows on VirtualBox and the exact same file that I was unable to upload from linux was uploaded for windows. I mean, the only thing that changes is the OS of client machine. Any way, I think is related to the file type restriction, because if I take out these restrictions I can upload the file from my ubuntu....
Codes are next:
form.php file:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input name="file" type="file" size="50" /><br>
<p><input name="upload" type="submit" value="upload" />
<input name="action" type="hidden" value="upload" /></p></form>
upload.php file:
<?php
$status = "";
if ($_POST["action"] == "upload") {
// data from file
$size = $_FILES["file"]['size'];
$type = $_FILES["file"]['type'];
$file = $_FILES["file"]['name'];
$pos = strpos($file, "_timetable.csv");
if ($file != "") {
if ($type == "text/csv" || $type == "application/vnd.ms-excel") {
if ($pos == false) {
$status = "Error: only files with extension <b>_timetable.csv</b> are allowed
<p><form action=\"form.php\"><input type=\"submit\" value=\" Select a different file \"></p>";
}else {
$destination = "filess/".$fitxer;
if (copy($_FILES['file']['tmp_name'],$destination)) {
$status = "<p>Uploaded: ".$file."</p>
}
else {
$status = "Error when uploading file<p><form action=\"form.php\"><input type=\"submit\"
value=\" Try again \"></p>";
}
}} else {
$status = "Error: only files with extension <b>_timetable.csv</b> are allowed
<p><form action=\"form.php\"><input type=\"submit\" value=\" Select a different file \"></p>";
}
} else {
$status = "Error when uploading file<p><form action=\"form.php\"><input type=\"submit\"
value=\" Try again \"></p>";
}
}
echo $status;
?>

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

Categories