I'm doing a file upload using https://github.com/danialfarid/ng-file-upload but I don't understand whether I'm actually sending the file or not. The payload just says:
------WebKitFormBoundaryaym16ehT29q60rUx
Content-Disposition: form-data; name="file"; filename="webfonts.zip"
Content-Type: application/zip
------WebKitFormBoundaryaym16ehT29q60rUx--
I don't understand what this means? It sort of looks like its being uploaded but the POST comes back instantly and I expected to see some sort of file stream. Whats going on, am I sending the file or not?
Each item in a multipart message is separated by a boundary marker. Webkit based browsers put "WebKitFormBoundary" in the name of that boundary.
The Network tab of developer tools do not show file data in a multipart message report: They can be too big.
Use a tool like Charles Proxy to watch the request instead if you want to monitor exactly what is in there.
That is the payload of the temporary image or document in post method. You can access the above code using php.
<?php
print_r($_FILES); // to print the file type params
$target_dir = "/var/www/html/me_docs/";
$date = date_create();
$timestamp = date_timestamp_get($date);
$filename = pathinfo($_FILES["filepond"]["name"],PATHINFO_FILENAME);
$extension = pathinfo($_FILES["filepond"]["name"],PATHINFO_EXTENSION);
$fullname = $filename.'_'.$timestamp.'.'.$extension;
$target_file_name = $target_dir.$fullname;
if(move_uploaded_file($_FILES["filepond"]["tmp_name"], $target_file_name))
{
echo "moving file success";
}
else
{
echo "failed moving file";
}
I hope it is useful for someone, Thank you.
Related
The issue I'm facing is, I get the following error while trying to upload some pdfs your upload file is not PDF file. However, this error doesn't show up for all pdfs, it's only for some pdf files I get this error.
<?php
$error = $_FILES['fileToUpload']['error'];
//get upload file type
$type = $_FILES['fileToUpload']['type'];
$action = "upload";
//get file name
$picname = $_FILES['fileToUpload']['name'];
$nameArray = explode(".", $picname);
if {
//check files
//filetoUpload code
}
?>
The issue is that, in the url: '../controller/uploadFile.php' even if the file is PDF, $type = $_FILES['fileToUpload']['type']; will return empty and then it will go into the condition else if($type !="application/pdf" ) and pop up the alert your upload file is not PDF file.. Like I said, this issue is with most of the pdf file. However, some pdf files manage to get uploaded without any issue and if a pdf file gets uploaded, then $type will be application/pdf.
Your input will be highly appriciated.
---UPDATE---
The issue is with $_FILES, it's not fetching the pdf file details for some reason
The issue has been resolved. I checked '$error= $_FILES['fileToUpload']['error']; and the value was returning 1
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.```
You could better check the extension, this also prevents malicious users to upload exe or zip files when they provide the header Content-Type: application/pdf. Also not all browsers/api libraries specify a Content-Type.
If your filename does not contain a path, check it with a regex so people cannot upload files to directories they shouldn't (ex ../../cache/exe). use for example
preg_match("/^[a-zA-Z0-9_+\\- ]+\\.pdf$/", $filename) to check if it is a pdf.
Do never do unlink('files/' . $filename); when $filename could be anything submitted by the user. Delete ../index.php could destroy your server.
I have a web app, where pdfs need to be generated dynamically. Data is gathered in javascript and send with a post request to the server. Here mpdf is used to generate a pdf. If I save the file locally: php $mpdf->Output($filename, \Mpdf\Output\Destination::FILE); it works.
But if I send it to the browser php $mpdf->Output($filename, \Mpdf\Output\Destination::DOWNLOAD); and take the output in the jquery callback to do the following (borrowed from https://nehalist.io/downloading-files-from-post-requests/):
jQuery.post(my_axax_url, data, function(data) {
var blob = new Blob([data], { type: 'application/pdf' });
var l = document.createElement('a');
l.href = window.URL.createObjectURL(blob);
l.download = 'test.pdf';
document.body.appendChild(l);
l.click();
});
The downloaded pdf is empty (blank page), and has corrupted author information (that makes it look, like an encoding problem). I ran https://www.datalogics.com/products/pdftools/pdf-checker/, which only gave me it the javascript generated pdf is a "Damaged document".
I hope, that this is an easy problem. I am used to php and text documents, not pdf.
Thanks!
Try adding the following to the start of your php script, it may be some sort of encoding issue:
ob_clean();
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="test.pdf"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
i have a pdf file that if downloaded through the viewer it downloads at the correct file size but when i use this code for say download selected the file size of the pdf changes and renders it useless when you open with adobe/nitro/etc.
<?php
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 'Off');
if (isset($_GET['url'])) {
$fullPath = $_GET['url'];
if($fullPath) {
#$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
header("Content-type: application/pdf"); // add here more headers for diff. extensions
break;
default;
header("Location: ".$fullPath);
exit;
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
fopen($fsize, "r");
exit;
}
}
?>
i noticed the file size is 24kb on the server. i go to url and view it then click the download from pdf viewer the file downloads just fine and verified the filesize in my download folder at 24kb. however when i use this code above as my download.php it downloads but comes back as 2kb.
can someone help me figure out why its changing the file size please?
I don't see any code where you are actually sending the file.Make sure you actually send the file. You have used fopen() but you are not using fread() that's why files is getting opened but not getting being read may be that's why it's showing some default output which amounts to 2kb . You can use the much simpler readfile() instead
For that replace this line
fopen($fsize, "r");
with this one
readfile('path/to/' . $path_parts["basename"]);
Just in case you are handling huge files like several MBs then fopen will suite you better as it would be more memory efficient.Also note the b flag in fopen() parameter it refers to binary mode so whenever you are sending a binary file like pdf,images etc you should always use this flag
set_time_limit(0);
$file = #fopen('path/to/' . $path_parts["basename"],"rb");
while(!feof('path/to/' . $path_parts["basename"]))
{
print(#fread('path/to/' . $path_parts["basename"], 1024*2));
ob_flush();
flush();
}
the problem was the / in the url it was starting with. once i added a trim to the url it worked. tbh now that i started looking into this i dont think it really ever work just appeared it did.
$trmfullPath = $_GET['url'];
$fullPath = trim($trmfullPath, "/");
this seemed to fix it. also dont get any errors in my php error log now.
I want to take the image data from my canvas on the client and save it as a .png on my server.
This is the code on my client that gets the image data from the canvas and sends it to saveImage.php:
function render()
{
var imageData = ctx.canvas.toDataURL("image/png");
var postData = "imageData="+imageData;
var ajax = new XMLHttpRequest();
ajax.open("POST","saveImage.php",true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.onreadystatechange=function()
{
console.log(ajax.responseText);
}
ajax.send(postData);
}
And this is what saveImage.php looks like:
<?php
if(isset($_POST["imageData"]))
{
$imageEncoded = $_POST["imageData"];
$imageDataExploded = explode(',', $imageEncoded);
$imageDecoded = base64_decode($imageDataExploded[1]);
$filename = time()."image".mt_rand();
$file = fopen("./".$filename.".png","wb");
fwrite($file, $imageDecoded);
fclose($file);
echo $filename;
exit();
}
?>
The code actually works fine, my problem is just that the images that gets created are faulty in some way.
When I try to open one, windows says that it cant show me the image because it doesn't support the format? even though its a .png?
what am I doing wrong here?
You should be encoding your data with encodeURIComponent() before including it in POST data.
You should also be using a framework like jQuery to account for browser differences. I guarantee that code will not work the same in all browsers.
On the PHP, try looking into file_put_contents() for writing data. Much quicker to type!
Have you checked what is actually being sent over HTTP? $imageEncoded probably starts with data:image/png;base64,xxxxx
Strip everything up to the comma after base64:
https://stackoverflow.com/a/15153931/3766670
I'm making a PHP script for a JavaScipt site I've made.
The goal is to save the contents of a string as an HTML file when I click a button.
I'm using jQuery to make a Post request.
I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).
A requirement is the PHP must live in another file.
The issue is whenever I make the request, the file saves blank.
A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.
So far, here is my code:
<?php
$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];
$htmlToSave = (string)$htmlImport;
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
?>
I've tried the frwite function that I've commented out, same effect.
I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.
The JS I've made to run my site looks like:
var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
.done(function(){
alert('Your file saved as ...' + htmlToSave)
})
I've also tried this code, with the same result:
$.post('saveHTML.php/', {
fileNameData : fileName,
htmlToSaveData : htmlToSave
})
Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.
Does anyone have ideas about what's going on here? I'm not a PHP developer at all.
I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.
I've read and tested the recommendations on this question here and this has been fruitless.
EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.
I can see right off the bat that you have
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
file_put_contents takes a file name, not a handle. So you would only need
file_put_contents($fileName, $htmlToSave);
Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.