Failed - Server Problem while Downloading File from URL in PHP - php

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>

Related

Failed to open pdf file [duplicate]

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?

download file using php, file is stored in a folder and name of the file is stored in database

I am trying to download a file from mysqli database using php for that i have stored file in a folder and file name is stored in the mysqli database.
here is my code...
$query= mysqli_query($dbo,"SELECT * FROM diff_questions WHERE email = ' $email ' and status= '0' ");
$rows=mysqli_fetch_array($query);
$file=$rows['file'];
$path='http://localhost/admin1/uploads';
?>
echo "<a href='download.php?file=".$file."&path=".$path." '>Download File</a> ";
and now
download.php-
<?php
$file = $_GET["file"];
$path = $_GET["path"];
$fullfile = $path.$file;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . Urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . Filesize($fullfile));
flush();
$fp = fopen($fullfile, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
?>
Can someone please tell me what is wrong with code. Its not working .
i mean it working file till saving file but its not downloading full file imean afther downloading file size of file is 0kb
Once replace your download.php with following code and check if its working for you or not :
if(isset($_GET["file"])){
$file = $_GET["file"];
$path = $_GET["path"];
$fullfile = $path.$file;
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . Urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
$fp = fopen($fullfile,'r');
while ($line = fgets($fp)) {
echo($line);
}
fclose($fp);
}

How can I add a download button?

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);

Downloading File via php script

I just switched from 000webhost(free) to godaddy(paid) servers and so far, it's like 10x worse than 000webhost >.>
Anyways, my problem is with the downloads. I use the following code and it worked fine on 000webhost to allow users to download rar files but now on godaddy, the rar file would return a end of archive error. I checked via FTP, the files are have not been corrupted via upload
<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$IP1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
$IP2 = $_SERVER['REMOTE_ADDR'];
$HWID = $_GET['HWID'];
date_default_timezone_set('America/New_York');
$date = date("m/d/y g:i:sA", time());
$file = $_GET['file'];
file_put_contents('Logs/Downloaded.txt', "IP: " . $IP2 . " Downloaded On: " . $date . " File: " . $file . " User Agent: " . $userAgent . "\n", FILE_APPEND);
$path = "files/";
$fullPath = $path.$file;
if(file_exists($fullPath)){
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
break;
case "zip":
header("Content-type: application/zip");
break;
default;
header("Content-type: application/octet-stream");
}
header("Content-Disposition: attachment; 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;
ob_flush();
flush();
}
}
fclose ($fd);
exit;
}else{
die("File could not be found");
}
?>
Does the script complete? You might need set_time_limit(0) to ensure it completes.
The other thing would be open the downloaded file in a hex editor and look for anomalies - I suspect you might have a PHP warning in there. You are calling ob_flush in your output loop, but as far as I can tell you're not performing any output buffering. It's possible that is triggering a warning, corrupting your output.

PHP download .jpg or .avi

I have gotten a problem about downloading .jpg and .avi files from a server using PHP
I have the following code:
$fileName = "Koala.jpg";
$filePath = "./Koala.jpg";
if (!file_exists($filePath)){
echo "No file";
return;
}
$fp = fopen($filePath, "r");
$fileSize = filesize($filePath);
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Content-Length: $fileSize");
header("Content-Disposition: attachment;filename=".$fileName);
$buffer = 1024;
while(!feof($fp)){
$data = fread($fp, $fileSize);
echo $data;
}
fclose($fp);
The code downloads .txt file successfully and the downloaded file can be read.
However, when it comes to .jpg, the downloaded .jpg file cannot be read.
Can anyone give a helping hand? Thanks
Have just tried another method and it works fine
$file = 'Koala.jpg';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
But just wonder what reason causes the first method fail, even though using fopen("xxx", "rb") instead. Thank you
Try replacing application/octet-stream for image/jpeg .
Regards
I'm no php expert (sorry to say) but I remember having a similar problem when using php on a Windows server. It stemmed from opening the file without the binary-flag (should be fopen($filePath, "rb"); in your sample). If you don't set that flag your data might be altered when you read it from the stream which could break your files (and you wouldn't notice it on textfiles).
See http://www.php.net/manual/en/function.fopen.php for more info on the different modes available.
Try using this --
<?php
$filename = "MyImage.jpg";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Instead of the following code that you are using,
$buffer = 1024;
while(!feof($fp)){
$data = fread($fp, $fileSize);
echo $data;
}
Just use readfile method
readfile($filePath);

Categories