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;
}
}
?>
Related
I have a download media function in which all type of media files gets downloaded. Below is the code
public function downloadMedia($file, $filename_direct = '', $extern = '', $exitHere = 1)
{
jimport('joomla.filesystem.file');
clearstatcache();
if (!$extern)
{
if (!JFile::exists($file))
{
return 2;
}
else
{
$len = filesize($file);
}
}
else
{
/* Return the size of a remote url or a local file specified by $url.
$thereturn specifies the unit returned (either bytes "", MiB "mb" or KiB
"kb"). */
$len = filesize($file);
}
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename, "."), 1));
$ctype = $this->getMime($file_extension);
ob_end_clean();
// Needed for MS IE - otherwise content disposition is not used?
if (ini_get('zlib.output_compression'))
{
ini_set('zlib.output_compression', 'Off');
}
header("Cache-Control: public, must-revalidate");
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header("Expires: 0");
header("Content-Description: File Transfer");
header("Content-Type: " . $ctype);
header("Content-Length: " . (string) $len);
header('Content-Disposition: attachment; filename="' . $filename . '"');
// set_time_limit doesn't work in safe mode
if (!ini_get('safe_mode'))
{
#set_time_limit(0);
}
/*#readfile($file);
if ($exitHere == 1)
{
exit;
}*/
$fp = fopen($file, "r") ;
ob_clean();
flush();
while (!#feof($fp)) {
$buff = #fread($fp, $len);
print $buff;
}
exit;
}
Now the issue is, whenever I download the PDF file & clicked on downloaded file it shows an error in a browser like 'Failed to load PDF document.'
The downloaded PDF file is opened correctly only when if I open the file in adobe instead of opening it in browser.
I have the following code in my Phalcon application.
public function downloadAction($key = NULL) {
if ($key == NULL) {
return $this->respondDownloadFailed();
}
$url = Urls::findFirst("token = '".$key."'");
if ($url) {
$path = $url->getUrl();
$ext = pathinfo($path, PATHINFO_EXTENSION);
header("Content-type: application/".$ext);
header("Content-Disposition: attachment; filename=".$key.".".$ext);
header("Content-length: " . filesize($path));
header("Pragma: no-cache");
header("Expires: 0");
ob_clean();
flush();
readfile($path);
unlink($path);
die;
}
return $this->respondDownloadFailed();
}
Now, when the .zip is created on the server I can open and unzip it. However, when I download it through the code above, I get a zip file which then unarchives to a .cpgz file. When unarchiving that one, I get a .zip again. Any ideas as to what is going wrong?
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?
I need help because I got an error message like "call to a member function mysql query on resource"
Here is my code:
<?php
include "koneksi.php";
$id_data = $_GET['id_data'];
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$query = "SELECT * FROM kinerja WHERE id_data = $id_data";
$hasil_data = $koneksi->query($query);
if ($hasil_data->num_rows > 0) {
// output data of each row
while($row = $hasil_data->mysql_fetch_assoc()) {
$filename = $row['nama_file'];
}
}
$path = "../admin/files/"; // change the path to fit your websites document structure
//$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
//$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$filename;
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");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
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;
?>
I need help for this code, I really apreciate any help. Sorry for my bad English.
It looks like the error is somewhere in koneksi.php. I would guess it's near the function query() in that class. If you include that class it would be easier to spot the error.
Hey i have following code to download a large file but the download does stop everytime without finish the download
function download($file)
{
include('logger.php5');
$log = new Logging();
$log->lfile('download.log');
ini_set('max_execution_time', 86400);
//header('Location: '.$file);
$filesize = filesize($file);
$filename = pathinfo($file, PATHINFO_BASENAME);
$filext = pathinfo($file, PATHINFO_EXTENSION);
$mime = include('mime.php5');
$log->lwrite(ini_get('max_execution_time'));
$log->lwrite(sprintf('%s %s %s %s', $filename, $filext, $mime[$filext], human_filesize($filesize)));
$log->lclose();
#ob_end_clean();
session_write_close();
header("Content-Description: File Transfer");
header("Content-Type: ".$mime[$filext]);
header("Content-Disposition: ".
(!strpos($HTTP_USER_AGENT,"MSIE 5.5")?"attachment; ":"").
"filename=".$filename);
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$filesize);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header('Pragma: public');
header('Expires: 0');
$done = readfile_chunked($file);
}
function readfile_chunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
Each time i call the script the download start up but stops after 400MB, the file itself is 778MB big.
Someone can see a problem with the code?
UPDATE
after try to log the return value of readfile_chunkedit feels like the script gets stoped not the download itself. Because i cant get a log entry after the readfile_chunked call.
It could be a problem with the filesize function in PHP. There are known bugs for big file size reading and as you're sending it with the file as an header I would suggest you to try the script without using this line:
header("Content-Length: ".$filesize);
Oh and maybe you can take a look at this line:
header("Content-Transfer-Encoding: binary");
I think the encoding should be checked for each file. Like this:
$finfo = finfo_open(FILEINFO_MIME);
//check to see if the mime-type starts with 'text'
return substr(finfo_file($finfo, $filename), 0, 4) == 'text';
If it's a textfile you should use ASCII ofcourse. Has nothing to do with the question but I think it's an useful addition to your script :)