i wrote code for downloading rar file it work's fine but
$name = 'file.rar';
$data = file_get_contents("file.rar");
$fh = fopen("$name", 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$name").";");
header("Content-Disposition: attachment; filename=$name");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
readfile($name);
exit;
after downloading , it shows an error unexpected end of archive while open that file,
it won't extract completely give me some suggestions thank you in advance
you can make ZIP file using following code on your web server
<?php
$za = new ZipArchive();
$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
$za->addFile('index.txt', 'newname.txt'); // original file , file to be added in zip
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";
for ($i=0; $i<$za->numFiles;$i++) {
echo "index: $i\n";
print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>
After that you can give link for download..
This file.rar is generating via code?
I have tried your code without these code
$data = file_get_contents("file.rar");
$fh = fopen("$name", 'w') or die("can't open file");
fwrite($fh, $data);
fclose($fh);
Its working fine for me.
Related
I am new to PHP and am trying to create a ZIP function which is called through Ajax and downloaded to the user.
I get a positive response with the zip but the streaming gives me an error for
filesize():stat failed for ../test.zip and also read file failed to open stream, no such file or directory on the PHP page.
Here is my code below - I have seared pretty hard and can't seem to find an answer that makes sense for my situation
<?php
require("../../common.php");
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
$thisdir = " ";
$zip = new ZipArchive();
$filename = "../test.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString('insert.pdf' . time(), "#1 This is a test string added as testfilephp.txt.\n");;
$zip->addFile($filename . "../../../folder/pdf_folder/");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
echo $filename;
//$size = filesize($zip->filename);
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$filename");
header("Content-length: " . filesize($filename));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$filename");
?>
thank you for any help or guidance
****** edit
here is the error for the code
Warning: filesize(): stat failed for ../test.zip in /var/---/----/---/----/control/ajax/zipAJAX.php on line 21
Warning: readfile(../test.zip): failed to open stream: No such file or directory in /var/---/----/---/----/control/ajax/zipAJAX.php on line 24
You can't add the contents of a folder to a zip file with the addFile method. You have to loop the directory (http://php.net/dir) and add each file to your zip with the addFile method.
Before you send any data back to the user, you can check if the zip file exists.
$zip->close();
if(file_exists($file)) {
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$filename");
header("Content-length: " . filesize($filename));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$filename");
}
Also check that the user has write permission in the directory where you want to place the zip file.
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?
Here is my code. Its working properly and now i want to compress the csv file before generate. Anybody please suggest me what to do!
$filename = 'Product_Export_' . date('Y-m-d') . '.csv';
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=' . $filename);
echo "\xEF\xBB\xBF"; // UTF-8 BOM
// clean the output buffer
ob_clean();
echo trim($_SESSION['cProductCSVdata']);
$_SESSION['cProductCSVdata'] = '';
exit;
Sending it to a zip file with ZipArchive is your solution.
Here is an example with .txt files.
<?php
$zip = new ZipArchive();
$filename = "./test112.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>
I'm trying to create a code that, based on informations from BD, creates a bibtex archive. That's what I got:
<?php
include("classe/conexao.php");
session_start();
$_SESSION[id_tese_especifica] = $_GET['id'];
$result = pg_query("SELECT titulo, id, data, autor_nome FROM teses ORDER BY data DESC");
$arr = pg_fetch_array($result);
echo "#phdthesis{phpthesis,
author={" . $arr[0] . "},
title={" . $arr[6] . " " . $arr[3] . "},
month={" . $arr[2] . "}";
$name = $_GET['id'] . ".bib";
$file = fopen($name, 'a');
$text = "test (it doesn't appears on archive and I don't know why, so I used the echo above and worked, but this is what should be on archive, or isn't?)";
fwrite($file, $text);
readfile($file);
fclose($fp);
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Expires: 0');
?>
After that, it downloads an archive named 'Resource id #6', why? The name should be based on this: $name = $_GET['id'] . ".bib".
Thanks!
Because filename is stored in a $name variable in your code:
header('Content-Disposition: attachment; filename="' . $name . '"');
And $file variable is a resource, connected with open file.
And by the way - you don't close the file properly.
fclose($fp); // $fp is NOT defined, your pointer is in $file variable
Proper code for closing is:
fclose($file);
Next, rearrange your code.
First of all - headers should be sent BEFORE any output.
What you currently have is some mix of errors, which accidentally show you something that you want.
Proper code should be:
$name = $_GET['id'] . ".bib";
// first of all - set proper headers:
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Expires: 0');
// next - do a query
$result = pg_query("SELECT titulo, id, data, autor_nome FROM teses ORDER BY data DESC");
$arr = pg_fetch_array($result);
// use echo for testing purposes only
// cause echo considered as a content of your file
echo "#phdthesis{phpthesis,
author={" . $arr[0] . "},
title={" . $arr[6] . " " . $arr[3] . "},
month={" . $arr[2] . "}";
$fp = fopen($name, 'a');
$text = "test (it doesn't appears on archive and I don't know why, so I used the echo above and worked, but this is what should be on archive, or isn't?)";
fwrite($fp, $text);
fclose($fp); // don't forget to close file for saving newly added data
readfile($name); // readfile takes a filename, not a handler.
die(); // end your script cause in other case all other data will be outputted too
Is it possible to create file.txt on the fly download it?
The file should be stored in backup/process/_pro_links_date.txt
but when I download the file, it has no .txt extension and it was store on my folder.
HTML
File
PHP
if ( $_GET['down'] == 'load' ) {
$date = date( 'Y-m-d H:i:s' );
$myFile = "backup/process/_pro_links_$date.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Title - Url - Live Date - Process Date \r";
fwrite($fh, $stringData);
$sql = mysql_query("SELECT * FROM k_addlinks WHERE user_code = '".$_SESSION['user_code']."' ") or die (mysql_error());
while ($row = mysql_fetch_array($sql)){
$dated = date("m/j/y g:i",strtotime( $row["date"] ));
if($row["spider_date"] == 'never'){
$sdate = $row["spider_date"];
}else{
$sdate = date("m/j/y g:i",strtotime( $row["spider_date"] ));
}
$stringData = $row['pro_name'] . $row['customDomain'] . $dated . $sdate . '\r';
}
fwrite($fh, $stringData);
fclose($fh);
$path = "backup/process/_pro_links_$date.txt";
$name = "_pro_links_$date.txt";
header("Content-Type: text/plain");
header("Content-Length: " . filesize($path));
header('Content-Disposition: attachment; filename='.$name);
readfile($path);
}
what is wrong with my codes?
I see the issue. In your Content-Disposition header, you set the filename, but your filename contains spaces since you created it using date("Y-m-d H:i:s"). So you need to surround the filename with quotes in that header:
// $name contains a space, in the format _pro_links_Y-m-d H:i:s.txt
$name = "_pro_links_$date.txt";
// Surround the filename with quotes...
header('Content-Disposition: attachment; filename="'.$name . '"');
Alternatively, remove the spaces from $date before using it in the filename:
$date = str_replace($date, " ", "_");
$name = "_pro_links_$date.txt";
Instead of saving it to a file, just echo it after you send the headers.
$content = "Hello world !!!";
$name = "name.txt";
$file = fopen($name,"wb");
fwrite($file, $content);
fclose($file);
header('Content-Type: charset=utf-8');
header("Content-disposition: attachment; filename=$name");
print $content;