This question already has answers here:
Chrome has "Failed to load PDF document" error message on inline PDFs
(7 answers)
Closed 5 years ago.
My code is working fine. My files are downloading also but when I open one file then it is not opening giving an error "Error
Failed to load PDF document."
<?php
$pno = $_GET['pno'];
$sql = "SELECT file FROM tenders WHERE Tno = $id";
$file = "data/" . $mysql_row['file '];
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='downloaded.pdf'");
readfile($file);
?>
$file = "path_to_file";
$fp = fopen($file, "r") ;
header("Cache-Control: maxage=1");
header("Pragma: public");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$myFileName."");
header("Content-Description: PHP Generated Data");
header("Content-Transfer-Encoding: binary");
header('Content-Length:' . filesize($file));
ob_clean();
flush();
while (!feof($fp)) {
$buff = fread($fp, 1024);
print $buff;
}
exit;
I would recommend to always check if the file exists. If it doesn't readfile() would eventually put an error inside your pdf-file which may cause the problem. Try it like this:
$pno = $_GET['pno'];
$sql = "SELECT file FROM tenders WHERE Tno = $id";
$file = "data/" . $mysql_row['file '];
if(file_exists($file)){
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='downloaded.pdf'");
readfile($file);
} else {
echo "File does not exist!";
}
Also there is no declaration of the $id variable. Could it be that $pno should be changed to $id?
Related
This has been really annoying me. When I try to download a file, it says Failed - Server problem.
But Its actually working well, when I declare the file path directly
$file = "wp-content/Devis_10.pdf";
But However I am trying to change the file path depending on the user sales id, is this case it shows download error.
$part2 = $current_user->sales_id;
$part1 = "wp-content/Devis_";
$part3 = ".pdf";
What am I missing here ??
This is my complete code
<?php
global $current_user;
get_currentuserinfo();
$email = $current_user->user_email;
$part2 = $current_user->sales_id;
$part1 = "wp-content/Devis_";
$part3 = ".pdf";
header("Content-Type: application/octet-stream");
$file = $part1.$part2.$part3; //Result example "wp-content/Devis_10.pdf";
header('Content-Disposition: attachment; filename="Devis.pdf"');
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
?>
HTML
<a href="https://www.xxxxxxxx.com/devis.php" download="Devis.pdf">
<button type="button">Download</button>
</a>
This question already has answers here:
Forcing to download a file using PHP
(10 answers)
Closed 4 years ago.
i have this code that work for me on other projects but now instead to download the file is show the file on browser
$query = "SELECT * FROM leads";
$result = $dbconn->query($query);
$filename = "leads_shaldor_" . date("Y-m-d H:i");
$filepath = "/var/www/vhosts/as7.co.il/shaldor.as7.co.il/exports/"
.$filename. ".csv";
$downpath = "http://shaldor.as7.co.il/exports/" .$filename. ".csv";
$csvFile = fopen($filepath, 'w') or die("can't open file");
fprintf($csvFile, chr(0xEF).chr(0xBB).chr(0xBF));
while($row = $result->fetch_assoc()){
fputcsv($csvFile,
array($row['id'],$row['name'],$row['phone'],$row['date']));
print_r($row);
}
fclose($csvFile);
header("Location: " . $downpath);
$result->close();
$sql->close();
$downpath = "http://shaldor.as7.co.il/exports/" .$filename. ".csv";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($downpath) . "\"")
Set the following headers. It should force a download. Your browser is opening it because it knows how to render the file.
refer to this answer:Forcing to download a file using PHP
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
You can use This.
To brute force all CSV files on your server to download, add in your .htaccess file:
AddType application/octet-stream csv
PHP Solution
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
On my website i allow a user to download a biography someone else posted while filling out a form. The problem I am recieving is that when I open a downloaded "txt" file, it opens fine but, when its like "docx or accdb" file, I get error messages like
We're sorry. We can't open xxx because we found a problem with its contents.
Details>>
The file is corrupt and cannot be opened
and I believe the problem happens when I get the file from the user. Here is my code
Upload file
$bio_name = $_FILES['biography']['name'];
$bio_tmp = $_FILES['biography']['tmp_name'];
$bio_size = $_FILES['biography']['size'];
$bio_type = $_FILES['biography']['type'];
$ext = pathinfo($bio_name, PATHINFO_EXTENSION);
if($ext=="pdf"||$ext=="PDF"||$ext=="doc"||$ext=="DOC"||$ext=="docx"||$ext=="DOCX"
||$ext=="XLS"||$ext=="xls"||$ext=="XLSX"||$ext=="xlsx"||$ext=="xlsm"||$ext=="XLSM"){
$fp = fopen($bio_tmp, 'r');
$content = fread($fp, filesize($bio_tmp));
$content = addslashes($content);
fclose($fp);
}else{
echo "<script>
alert('ERROR: This file format is not supported');
window.location.href='form.php';
</script>";
}
Download file
$size = $formData['bio_size'];
$type = $formData['bio_type'];
$file = $formData['bio_filename'];
$content = $formData['bio_tmp'];
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$file");
ob_clean();
flush();
echo $content;
The query returns 71 rows but only one image is downloaded. All image files are jpegs with 2 MB maximum file size; most are less than 1 MB. The fsize lines are commented out because they fail to return on the jpg image file.
I have no trouble opening the one image downloaded so I'm doing something right. How can I get the other 70 images? I'm not deep in PHP but I get done what I need to get done. Here's my code:
<?php
$query = "SELECT imagefilename FROM imageinfo WHERE accepted = 1 ";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result))
{
$imagefilename = $row[0];
$sourcefile = 'http://domain.com/images/'.$imagefilename;
if ($fd = fopen ($fullPath, "r"))
{
//$fsize = filesize($sourcefile);
// if IE, otherwise Content-Disposition ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header("Content-type: image/jpg");
header("Content-Disposition: attachment; filename=$imagefilename");
//header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd))
{
$buffer = fread($fd, 2097152);
echo $buffer;
}
}
fclose ($fd);
} //end while
?>
Patching together several postings, here is the working code I ended with.
//This puts the selected images in a zip file.
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$query = "SELECT imagefilename FROM imagetable WHERE accepted = 1 ";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) == 0)
{
//Send message.
}
// common vars
$file_path = 'path_to_image_file';
$zipname = 'images.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipARCHIVE::CREATE );
while ($row = mysqli_fetch_array($result))
{
$filename = $row[0];
$zip->addFile($file_path.$filename,$filename);
}
$zip->close();
if (!file_exists($zipname))
{
//Send message
}
//This downloads the zip file.
//zip headers
if (headers_sent())
{
echo 'HTTP header already sent';
}
else
{
if (!is_readable($zipname))
{
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
}
else
{
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($zipname));
header("Content-Disposition: attachment; filename=\"".basename($zipname)."\"");
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipname);
exit;
}
}
?>
I have this code which outputs a QR code:
<?php
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('Soci', 'Nom', 'Cognoms', 'eCorreu')))
->from($db->quoteName('#__rsform_socis'))
->where($db->quoteName('username') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$codeContents = $db->loadObjectList();
$data .= "Soci NÂș: {$codeContents[0]->Soci}\n ";
$data .= "Nom: {$codeContents[0]->Nom} ";
$data .= "{$codeContents[0]->Cognoms}\n";
$data .= "e-correu: {$codeContents[0]->eCorreu}";
$tempDir = JPATH_SITE . '/images/';
$fileName = 'qr_'.md5($data).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = JUri::root() .'images/' . $fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($data, $pngAbsoluteFilePath);
}
echo '<img src="'.$urlRelativeFilePath.'" />';
?>
How can I add a download button so the user can download the code to the computer?
Thanks,
Dani
This is more of a HTML question, so lets get started: There is an attribute called "download" and you can use it like this:
echo 'Download QR';
It downloads the file as the name you supply here. So if the image url on your server is: wadAHEybwdYRfaedBFD22324Dsefmsf.png it would download the file as "qrcode.png". Unfortunately this is not supported in all browsers. Another easy fix is to make a form that has your filename as an action like so:
echo '<form method="get" action="'.$urlRelativeFilePath.'"><button type="submit">Download QR Code!</button></form>';
Another way (little more code) to do this is using PHP with some specific headers like this:
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// Download here
?>
It works for large and small files and also for many different filetypes. Info found here: http://www.finalwebsites.com/forums/topic/php-file-download
Well, you are obviously creating a .png picture file of the QR code with your script. So simply add a link to the location of the picture:
echo "Download";
This will however just redirect the user to the picture in his browser.
If you want to force a download you will need to use PHP headers to send the file to the visitors browser.
For example make a script and call it download_code.php.
Then add:
echo "Download";
And in the download_code.php:
$handle = fopen("/var/www/yourdomain.com/images/" . $filename, "r");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Length: ' . filesize("/var/www/yourdomain.com/images" . $filename));
flush();
readfile("/var/www/yourdomain.com/images" . $filename);
fclose($handle);