handle pdf form submitted as entire pdf using php - php

I've made a form that I want the user to submit as an entire PDF to be saved on the server. I've been trying to make a php script that handles the files coming in. Basically, I've taken the example from W3 schools and tried to adapt it:
<?php
$file = file_get_contents("php://input");
$target_dir = "uploads/";
$target_file = $target_dir . basename($file);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($file, $target_file)) {
echo "The file ". basename( $file). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
However, it's not working. I get the second error message: "Sorry, there was an error uploading your file."
I'm fairly new to php and would greatly appreciate some help.
Thanks!
UPDATE: All the documentation and examples involve POST data from an HTML form, so the input field name is known in each. My PDFs are generated server side with random names, so I had to adapt the examples. I made this one which worked with an HTML form:
<?php
foreach ($_FILES as $name => $value)
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES[$name]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES[$name]["tmp_name"], $target_file)
?>
However, when I submitted from the PDF itself using Adobe Acrobat, I got a series of errors:
http://localhost/save.php[22/01/2016 20:23:05]
Notice: Undefined variable: name in C:\xampp\htdocs\save.php on line 4
Notice: Undefined index: in C:\xampp\htdocs\save.php on line 4
Notice: Undefined variable: target_dir in C:\xampp\htdocs\save.php on line 4
Notice: Undefined variable: name in C:\xampp\htdocs\save.php on line 7
Notice: Undefined index: in C:\xampp\htdocs\save.php on line 7
Although my script uploads files from HTML forms without needing to know the input field name (which is always known in the documentation examples), which I was pleased about, it doesn't work when submitted from within the PDF itself.
Does anyone know why that would be?

If you submit a PDF form by sending the whole document, you just have to take the raw post data as the document data. There are no individual post fields but:
$fileContent = file_get_contents("php://input");
...is enough. You have the whole PDF document in $fileContent now. So just save this (after validation!) and you're done.

Related

How to catch an error for a file name error? [duplicate]

This question already has answers here:
PHP Upload IF ISSET always says it is?
(5 answers)
Closed 3 years ago.
I am working on an instagram clone for school and I am currently working on the "update profile" feature,whenever I try to update the profile picture it works like a charm, but whenever I dont update the profile picture but I just update the description or username I get the following error.
"getimagesize(): Filename cannot be empty"
What is the best way to catch this error when I am not uploading a new profile picture?
I have tried a "try catch" method but it doesn't seem to work.
(could be possible I implemented it the wrong way
if(isset($_FILES["file"])){
if(getimagesize($_FILES["file"]["tmp_name"]) !== false){
$target_dir = "uploads/";
$extention = explode(".", $_FILES["file"]["name"]);
$i = count($extention) - 1;
$target_file = $target_dir . basename($_FILES["file"]["tmp_name"] . "." . $extention[$i]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// File has been moved to Uploads/[temp_name].[extention]
$user->setImage($target_file);
$a["image"] = $target_file;
} else {
// The file did not move to the destonation folder
}
}
}
I expect this to not return the error to me when I am not uploading a new picture but just tring to update my username or description.
You can check if error index is zero (UPLOAD_ERR_OK), if error is not zero cause no file was uploaded, UPLOAD_ERR_NO_FILE will be there
If you just want to check if upload went good you can write:
if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
// file is good (and not an error)
}
If you want to check file wasn't uploaded
if ($_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
// file is empty, no upload
}
Check PHP Reference for more!

How to check for error file input before sending them through post

In the web page I have 2 tabs and 1 submit button. I first tab inputs with type=text. In second inputs with type=file. I wanna to send both tabs with 1 submit. But problem isn't here. In the second tab I need to check files for error before sending them. So If it has an error then submit button isn't active. How can I do this?
Now I check them for error only after sending them. And when some of the files have an error then upload fails and its return to page with an error. And all other files which haven't error disappear from the input .
First tab http://prntscr.com/mnzc79 . Second tab http://prntscr.com/mnzca3 .
Here all inputs are the document of the student in university. So I can use just multi upload. Because all of them are a different files. I can't understand the mechanism of uploading many file inputs with error check.
Here my code
Check if text inputs uploaded. If files were set then I push them to the array to use in query.
if(!empty($_POST["first_name"])){
$keys=$keys."first_name,";
$first_name=$_POST["first_name"];
$values=$values."'".$_POST['first_name']."',";
}
if(!empty($_POST["last_name"])){
$keys=$keys."last_name,";
$last_name=$_POST["last_name"];
$values=$values."'".$_POST['last_name']."',";
}
...
...
Check if files uploaded
if(isset($_FILES["zayavlenie_o_zachisleniy"]["name"]) && !empty($_FILES["zayavlenie_o_zachisleniy"]["name"])){
array_push($uploads,"zayavlenie_o_zachisleniy");
upload("zayavlenie_o_zachisleniy");
}
...
...
Here checks file for error and upload
function upload($filename){
if (!file_exists('student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo)) {
mkdir('student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo, 0777, true);
}
$target_dir = 'student_docs/'.$first_name.'_'.$last_name.'_'.$otchestvo.'/';
$target_file = $target_dir . basename($_FILES[$filename]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
.....
}
// Check if file already exists
if (file_exists($target_file)) {
.....
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
.....
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
.....
} else {
if (move_uploaded_file($_FILES[$filename]["tmp_name"], $target_file)) {
array_push($values,$target_file);
echo "The file ". basename( $_FILES[$filename]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
$sql="UPDATE students set $set where id='$student_id'";
for($i=0;$i<sizeof($uploads);$i++){
if($i==(sizeof($uploads)-1)){
$sql=$sql."'".$uploads[$i]."'";
}
else{
$sql=$sql."'".$uploads[$i]."',";
}
}
$db->insert($sql.")");
You can either do this with javascript or php. If you are checking if the file does already exist on your webserver, you can't do this ONLY using javascript. So you need to check this with php, cause php is running on your server. Javascript not.
So, when you encounter any error while uploading the files (like already existing files or wrong file formats) you can redirect the user to any page you want and cancel the request like this:
header("Location: http://YourErrorPage.com");
exit;

PHP Image Hashing in directory and database

I am still having trouble hashing my pictures when I upload them . I have this code :
$target_dir = "images/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
hash_file('sha256', $target_file );
// Check if image file is a actual image or fake image
if(isset($_POST["change"])) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$sql = "UPDATE users SET userPic = '".$_FILES['fileToUpload']['name']."' WHERE username = '" . $username . "'";
$check = $conn->query($sql);
if($check !== false) {
echo "<a href = profile.php> Profile pciture has been changed </a>" .
$check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
} else {
echo"did not change";
}
and I am getting this error :
Warning: hash_file(images/uploads/english_royal_family_tree.jpg): failed to open stream: No such file or directory
I have been trying for more than a week . No one is really helping and people just keep on voting down my question and aren't giving any help . Can someone please help me ?
Firstly, hash_file() is expecting a file to already exist and you're trying use that method before the file gets uploaded; that's why your code failed and threw you that error.
What you need to do is to see if that file exists and then hash it.
If this is really want you want to do, then you can base yourself on the following and remember to store the renamed file while retaining its original extension; there are links at the end of the answer.
Note: As I mentioned in comments, you need to hash the file and not the whole destination folder and the file. That would be impossible to retrieve.
Echo the variable for what was assigned to hash_file(). You will also get your hash name (only) shown minus its extension.
Check for errors and make sure the folder has been granted proper permissions.
<?php
// check for errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$file_name = $_FILES['fileToUpload']['name'];
$sent_file = move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
if (file_exists("images/uploads/" . $_FILES["fileToUpload"]["name"]))
{
echo $the_file = $_FILES["fileToUpload"]["name"] . " exists.";
// its new location and hashing the filename only.
$var = hash_file('sha256', $the_file );
echo $var;
// store your renamed file here in your database
// using the assigned $var variable.
}
Also check for errors on the query with mysqli_error($conn).
However, you're going to end up with problems here to show that image, since now and for example in using "file.jpg" will produce the following hash:
cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90
I don't know how you plan on showing the image(s), but it will no longer keep the .jpg extension.
In order to retain the image's file extension, you basically need to rename the uploaded file(s).
Here are a few good references on Stack (that I've had success with in the past) that you can look at and implement it in your code. :
How to rename uploaded file before saving it into a directory?
Rename uploaded file (php)
There is indeed no better way to learn, IMHO.
Edit:
This is an excerpt from a script I wrote recently. Base yourself on the following.
Note: You shouldn't use hashing methods such as anything from the SHA family or MD5 as the file name, since those produce the same hash and has no uniqueness to them.
Important: If people upload from a mobile device, most of them have "image.jpg" as the default name, so it needs to be renamed and given a unique method.
Using the date and time is one way. You can also add uniqid() to it by assigning a variable to it and append to the new file name, or a combination of MD5 and uniqid() is a good bet.
You will need to do a few modifications to it of course. The $year variable is something I used but you can get rid of those instances and replace them with your own.
$year = date("Y");
$pdf_file = $_FILES['fileToUpload']["name"];
$uploaded_date = date("Y-m-d_h-i-s_A"); // this could be another unique method.
$target_dir = "../upload_folder/" . $year . "/";
$ext = explode('.',$_FILES['fileToUpload']['name']);
$extension = $ext[1];
$newname = $ext[0].'_'.$uploaded_date;
$full_local_path = $target_dir.$newname.'.'.$extension;
$new_full_name = $newname.'.'.$extension;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $full_local_path)) {
echo "The file ". $newname . " has been uploaded.";
echo "<hr>";
$file_link = "/upload_folder/$year/$new_full_name";
// other code such as saving to a database...
}

Trouble uploaded multiple files and saving the paths to database

Ok Basically i am following this guide which is pretty straight forward but, I am at the point now where i am completely lost. I don't want to have to start all over again and I hope it's just a minor adjustment but anyhow heres the error:
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /I don't want to publicize the path name/html/add.php on line 39
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpqd62Gk' to 'thumbnails/' in /I don't want to publicize the path name/add.php on line 39
Sorry, there was a problem uploading your cover. Please check it is the appropriate size and format.
Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in /I don't want to publicize the path name/add.php on line 52
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpFVlGsv' to 'audio/' in /I don't want to publicize the path name/add.php on line 52
Sorry, there was a problem uploading your song. Please check it is the appropriate size and format.
And here is the "add.php" which is executed after submitting the form :
<?php
include "db_config.php";
//This is the directory where images will be saved
$targetp = "thumbnails/";
$targetp = $targetp . basename( $_FILES['cover']['artist']);
//This is our size condition
if ($uploaded_size > 100000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is the directory where songs will be saved
$targets = "audio/";
$targets = $targets . basename( $_FILES['song']['artist']);
//This is our size condition
if ($uploaded_size > 6000000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This gets all the other information from the form
$title=$_POST['title'];
$artist=$_POST['artist'];
$cover=($_FILES['cover']['artist']);
$song=($_FILES['song']['artist']);
$today = date("Ymd");
$ip = $_SERVER['REMOTE_ADDR'];
//Writes the information to the database
mysql_query("INSERT INTO `Thumbnails` VALUES ( '', '$artist - $title', '$cover', '', '$song', '$title', '$artist', '$today', '$ip')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['cover']['tmp_name'], $targetp))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['cover']['artist']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your cover. Please check it is the appropriate size and format.";
}
//Duplicate for song
if(move_uploaded_file($_FILES['song']['tmp_name'], $targets))
{
echo "The file ". basename( $_FILES['song']['artist']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your song. Please check it is the appropriate size and format.";
}
?>
Perhaps a step in the right direction would be greatly appreciated as it has gotten to the point where it all feels like scribble on a screen but, I'd hate to start all over again.
Try to
Change
basename( $_FILES['cover']['artist']);
To
basename( $_FILES['cover']['name']);
try
$targetp = "/thumbnails/;
$targets = "/audio/";
or specify full path name like c:/some/path/here

Undefined variable in upload script

I get following errors and I don't know why.
Notice: Undefined index: uploaded in C:\xampp\htdocs\site\upload.php on line 3
Notice: Undefined variable: uploaded_size in C:\xampp\htdocs\site\upload.php on line 7
Notice: Undefined variable: uploaded_type in C:\xampp\htdocs\site\upload.php on line 14
Notice: Undefined index: uploaded in C:\xampp\htdocs\site\upload.php on line 29
I tried to include the source of the php in this post but couldn't.
Here is link to pastebin: My source code
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
//This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Edit 1 : I got the code from about.com about.com
1.) In your $FILES array, there's no uploaded index defined. Possibly because it's $_FILES That's the first one. Try
<pre>
print_r($FILES);
print_r($_FILES);
</pre>
to see what is in there.
2.) ¿Where are you initializing those variables being used in the conditionals? You must extract data from the file element in the array and assign it to the variables before using it.
The first notice is telling you that on this line:
$target = $target . basename( $_FILES['uploaded']['name']) ;
There is no 'uploaded' index into the $_FILES array because no file was uploaded in a form with the file input named uploaded.
The next notice is telling you that on this line:
if ($uploaded_size > 350000)
You are accessing a variable named $uploaded_size which has never previously been defined, so how could it possibly hold some value greater than 350000?
Same issue with the next two notices. You seem to be missing some code, and are testing code for handling uploaded files without uploading a file, or without using a form with the enctype and input names it expects.
If you find that the $_FILES array does not contain any reference to your uploaded file, make sure your form tag includes enctype="multipart/form-data".

Categories