this code is doing Zip & Download perfect but i want to change a time to date how can i do this
when i save a folder its save with time i want to save with date how can i do this
this is time script how can i change in to date when i change Y-m-d but this is not working its showing this error Parse error: syntax error, unexpected T_STRING in downloadlist.php on line 26
please help me to fix this issue
thanks
$filename = Y-m-d " Backup.zip"; (not working)
$filename = time() ." Backup.zip"; ( working code)
downloadlist.php
<?php
// function download($file) downloads file provided in $file
function download($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, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
$files = $_POST['file'];
if(empty($files))
{
echo("You haven't selected any file to download.");
}
else
{
$zip = new ZipArchive();
$filename = time() ." Backup.zip"; //adds timestamp to zip archive so every file has unique filename
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { // creates new zip archive
exit("Cannot open <$filename>\n");
}
$N = count($files);
for($i=0; $i < $N; $i++)
{
$zip->addFile($files[$i], $files[$i]); //add files to archive
}
$numFiles = $zip->numFiles;
$zip->close();
$time = 8; //how long in seconds do we wait for files to be archived.
$found = false;
for($i=0; $i<$time; $i++){
if($numFiles == $N){ // check if number of files in zip archive equals number of checked files
download($filename);
$found = true;
break;
}
sleep(1); // if not found wait one second before continue looping
}
if($found) { }
else echo "Sorry, this is taking too long";
}
?>
list.php
<?php
function listDir($dirName)
{
$forbidden_files=array('.htaccess','.htpasswd');
$allow_ext=array('.pdf','.doc','.docx','.xls','.xlsx','.txt');
?><form name="filelist" action="downloadList.php" method="POST"><?php echo "\n";
if ($handle = opendir($dirName)) {
while (false !== ($file = readdir($handle)) ) {
$allowed=(strpos($file,'.')!==false && in_array(substr($file,strpos($file,'.')) ,$allow_ext ));
if ($file != "." && $file != ".." && $allowed ) { ?> <input type=checkbox name="file[]" value="<?php echo "$file";?>"><?php echo "$file"; ?><br><?php echo "\n";
}
}
closedir($handle);
}
?><br><input type="submit" name="formSubmit" value="Zip and download" /></form><?php
}
listDir('.'); ?>
$filename = Y-m-d " Backup.zip"; (not working)
because you are not using date() here. Also, you are not concatenating strings using ..
$filename = date('Y-m-d')."Backup.zip";
The above code will work for you.
Related
I am uploading text file and then converting it after conversion I am forcing it to auto download that converted text file, but it's not getting downloaded, giving error Warning: Cannot modify header information - headers already sent
Force download text file PHP code
if (file_exists($fileCreate)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileCreate));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileCreate));
ob_clean();
flush();
readfile($fileCreate);
exit;
}
}
Full PHP code
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(!empty($_FILES['uploaded_file']))
{
$path = "upload/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
$count = 0;
$fileCreate = 'order-'.date('m-d-Y').".txt";
$myfile = fopen("$fileCreate","w") or die("Unable to open file!");
fwrite($myfile, "1"."\n");
if($file = fopen("$path", "r")){
while(!feof($file)) {
$line = fgets($file);
$keywords = preg_split("/[\s,]+/", $line);
$x = $keywords[2];
$y = 5;
$y .= $x;
$y .= "001";
$date = $keywords[1];
$date1 = str_replace('"','',$date);
$newDate = date("Y/m/d", strtotime($date1));
$y .= str_replace("/", "", $newDate);
$y .= " ";
$fso = $keywords[3];
$fso = str_replace('"','',$fso);
$y .= $keywords[3];
if($fso != "FPO" || $fso != "APO"){
$y .= $keywords[4];
}
$y = str_replace('"','',$y);
$storeValue[$count]=$y;
fwrite($myfile, $y."\n");
$count++;
}
$str = strval($count);
$strlen = strlen($str);
if($strlen == 1){
$footer = 900000;
}
else if($strlen == 2){
$footer = 90000;
}
else if($strlen == 3){
$footer = 9000;
}
else if($strlen == 4){
$footer = 900;
}
else if($strlen == 5){
$footer = 90;
}
else{
$footer = 9;
}
$footer .= $count;
$footerDate = date("Y/m/d");
$footer .= str_replace("/", "", $footerDate);
fwrite($myfile, $footer."\n");
fclose($file);
}
if (file_exists($fileCreate)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileCreate));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileCreate));
ob_clean();
flush();
readfile($fileCreate);
exit;
}
}
?>
UPDATE: It's fixed by adding output_buffering = ON in php.ini file
Two things.
1) You need to start session immediately after the <?php
2) You session redirect does not work if something output before the session redirect (header location).
What you can do is,
You can use javascript for redirecting.
echo '<script>window.location.replace("http://stackoverflow.com");</script>';
Anyway if you are using sessions, start session on the top of page (session_start()).
<?php
session_start();
error_reporting(E_ALL & ~E_NOTICE);
if(!empty($_FILES['uploaded_file']))
Update
It's fixed by adding output_buffering = ON in php.ini file
I need to be able to do this.
From a form with checkbox the user select multiple images or singles images and then download it via PHP as a Zip file.
In that way it allows user to choose images he needs or not.
Here is my Code :
<form name="zips" action="download.php" method=POST>
<ul>
<li>
<input type="checkbox" class="chk" name="items[0]" id="img0" value="2015-Above-it-All"/>
<p>Above It All</p>
</li>
<li>
<input type="checkbox" class="chk" name="items[1]" id="img1" value="2015-Crocodile"/>
<p>Crocodile</p>
</li>
<li>
<input type="checkbox" class="chk" name="items[2]" id="img2" value="2015-Dandelion"/>
<p>Dandelion</p>
</li>
<li>
<input type="checkbox" class="chk" name="items[3]" id="img3" value="2015-Dearest-Sister"/>
<p>Dearest Sister</p>
</li>
<div style="text-align:center;" >
<input type="submit" id="submit" name="createzip" value="DOWNLOAD" class="subbutton-images" >
</div>
</form>
Then the PHP code:
<?php
// common vars
$file_path = $_SERVER['DOCUMENT_ROOT']."/img/press/";
if(count($_POST['file']) > 1){
//more than one file - zip together then download
$zipname = 'Forms-'.date(strtotime("now")).'.zip';
$zip = new ZipArchive();
if ($zip->open($zipname, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipname>\n");
}
foreach ($_POST['items'] as $key => $val) {
$files = $val . '.jpg';
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//zip headers
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} 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;
}
}
} elseif(count($_POST['items']) == 1) {
//only one file selected
foreach ($_POST['items'] as $key => $val) {
$singlename = $val . '.jpg';
}
$pdfname = $file_path. $singlename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($pdfname)."'");
header('Content-Length: ' . filesize($pdfname));
header("Cache-control: private"); //use this to open files directly
readfile($pdfname);
} else {
echo 'no documents were selected. Please go back and select one or more documents';
}
?>
At the moment this script let me download a single image from the form but as soon as there is 2 images and that the script try to ZIP the files and then offer download its not working anymore.
Any ideas would be pretty nice from you guys as i'm a bit stucked with the scfript at the moment?
So below is the right PHP script which works for me :
:))
<?php
// common vars
$file_path = $_SERVER['DOCUMENT_ROOT']."/img/press/";
if(count($_POST['items']) > 1){
//more than one file - zip together then download
$zipname = 'Forms-'.date(strtotime("now")).'.zip';
$zip = new ZipArchive();
if ($zip->open($zipname, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipname>\n");
}
foreach ($_POST['items'] as $key => $val) {
$files = $val . '.jpg';
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//zip headers
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$zipname);
header('Pragma: no-cache');
header('Expires: 0');
readfile($zipname);
flush();
if (readfile($zipname))
{
unlink($zipname);
}
//unlink($zipname);
exit;
}
}
} elseif(count($_POST['items']) == 1) {
//only one file selected
foreach ($_POST['items'] as $key => $val) {
$singlename = $val . '.jpg';
}
$pdfname = $file_path. $singlename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content- Disposition:inline;filename='".basename($pdfname)."'");
header('Content-Length: ' . filesize($pdfname));
header("Cache-control: private"); //use this to open files directly
readfile($pdfname);
} else {
echo 'no documents were selected. Please go back and select one or more documents';
}
?>
***<?php
// common vars
$file_path = $_SERVER['DOCUMENT_ROOT']."/img/press/";
if(count($_POST['items']) > 1){
//more than one file - zip together then download
$zipname = 'Forms-'.date(strtotime("now")).'.zip';
$zip = new ZipArchive();
if ($zip->open($zipname, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$zipname>\n");
}
foreach ($_POST['items'] as $key => $val) {
$files = $val . '.jpg';
$zip->addFile($file_path.$files,$files);
}
$zip->close();
//zip headers
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found';
} else if (!is_readable($zipname)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable';
} else {
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$zipname);
header('Pragma: no-cache');
header('Expires: 0');
readfile($zipname);
flush();
if (readfile($zipname))
{
unlink($zipname);
}
//unlink($zipname);
exit;
}
}
} elseif(count($_POST['items']) == 1) {
//only one file selected
foreach ($_POST['items'] as $key => $val) {
$singlename = $val . '.jpg';
}
$pdfname = $file_path. $singlename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content- Disposition:inline;filename='".basename($pdfname)."'");
header('Content-Length: ' . filesize($pdfname));
header("Cache-control: private"); //use this to open files directly
readfile($pdfname);
} else {
echo 'No Document were selected .Please Go back and Select Document again';
}
?>***
I have the following code to force download an IPA file (after codesigning it with a script). It works fine with smaller files but with larger files, my web server starts returning a 500 Internal Server Error. Would someone be able to help me tweak my existing code to overcome this issue?
$time = md5(time());
// Runs code signing script here
// And then attempts to initiate download
$path = "done/$time/";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$time.ipa");
header("Content-Type: application/ipa");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile("done/$time/".$latest_filename);
// header('location: dashboard.php');
} else {
// Throwback
die("Failed. Contact support. // <p>$sign</p>");
}
Here is an example:
$filepath = "done/{$time}/{$latest_filename}";
$size = filesize($filepath);
$mimetype = 'application/ipa';
// Turn off buffering
if (ob_get_level()) {
ob_end_clean();
}
$handle = fopen($filepath, 'rb');
if ($handle !== false && $size > 0) {
#flock($handle, LOCK_SH);
$filename = rawurldecode($filepath);
$old_max_execution_time = ini_get('max_execution_time');
$old_cache_limiter = session_cache_limiter();
ini_set('max_execution_time', 0);
session_cache_limiter(false);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-Type: ' . $mimetype);
header('Content-Transfer-Encoding: binary');
header('Content-disposition: attachment; filename="'. $filename .'"');
// or your variant
// header("Content-Disposition: attachment; filename=" . md5(time()));
header("Content-Length: $size");
$start = 0;
$end = $size - 1;
$chunk = 8 * 1024;
$requested = (float)$end - (float)$start + 1;
while (! $error) {
if ($chunk >= $requested) {
$chunk = (integer)$requested;
}
set_time_limit(0);
while (! feof($handle) && (connection_status() === 0)) {
if (! $buffer = #fread($handle, $chunk)) {
$error = true;
break 2;
}
print($buffer);
flush();
}
#flock($handle, LOCK_UN);
#fclose($handle);
ini_set('max_execution_time', $old_max_execution_time);
session_cache_limiter($old_cache_limiter);
break;
}
if ($error) {
// 500 - Internal server error
exit;
}
} else {
// Can't open file
exit;
}
Maybe problem in script time execution.
Try to set ini_set('max_execution_time', 0);
Also try to read and send file by chunks.
I am trying to read and get the size of the zip file in PHP.
Following is my code:
function create_zip($files, $file_name, $overwrite = false) {
foreach ($files as $imglink) {
$img = file_get_contents($imglink);
$destination_path = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/downloads/' . time() . '.jpg';
file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
foreach ($valid_files as $file) {
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/';
$fileSize = filesize($filepath . $filename) / 1024;
echo 'size of the file is : ' . $fileSize . ' kb';
exit;
// $size = 0;
// $resource = zip_open($filepath . $filename);
// while ($dir_resource = zip_read($resource)) {
// $size += zip_entry_filesize($dir_resource);
// }
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . zip_entry_filesize($filepath . $filename));
if (#readfile($filepath . $filename) === false) {
header('http://localhost/demoproject/fbindex.php');
return 500;
} else {
header('Location:http://localhost/demoproject/fbindex.php');
return 200;
}
} else {
return false;
}
}
$files : contain the array of images and
$file_name : contain name of file : that is : $file_name = time() . ".zip";
In the above code $filename contains the actual zip file and $filepath contains the location of the zip file.
The issue is it's reading the file but always showing its size 0 instead of actual file size.
This is I am doing :
echo $size;
O/P : 0
Where am I going wrong? Need Help. Thanks
try this -
$fileSize = filesize($filepath . $filename)/1024;
echo 'size of the file is : '.$fileSize.' kb';
Shouldn't you close ZIP file just after adding files to it?
$zip->close();
Try clearstatcache() just before calling filesize().
Closing your zip file before all this is also a great idea.
I know I'm a bit late on this, but who knows?
I'm trying to combine two CSV files in PHP. I'm looking for perfect method. Here's my code so far:
$one = fopen('data5.csv', 'r');
$two = fopen('userdata.csv', 'r');
$final = fopen('final_data.csv', 'a');
$temp1 = fread($one, filesize("data5.csv"));
$temp2 = fread($two, filesize("userdata.csv"));
fwrite($final, $temp1);
fwrite($final, $temp2);
I will give you a solution to use if you have big CVSs and you don't want to use much of your machine's RAM (imagine each CSV is 1GB, for example).
<?php
function joinFiles(array $files, $result) {
if(!is_array($files)) {
throw new Exception('`$files` must be an array');
}
$wH = fopen($result, "w+");
foreach($files as $file) {
$fh = fopen($file, "r");
while(!feof($fh)) {
fwrite($wH, fgets($fh));
}
fclose($fh);
unset($fh);
fwrite($wH, "\n"); //usually last line doesn't have a newline
}
fclose($wH);
unset($wH);
}
Usage:
<?php
joinFiles(array('join1.csv', 'join2.csv'), 'join3.csv');
Fun fact:
I just used this to concat 2 CSV files of ~500,000 lines each. It took around 5seconds and used 512kb of memory.
Logic:
Open each file, read one line and then write it to the output file. Yes, it may be slower writing each line rather than writing a whole buffer, but this allows the usage of heavy files while being gentle on the memory of the machine.
At any point, you are safe because the script only reads on line at a time and then writes it.
Enjoy!
How about...
file_put_contents('final_data.csv',
file_get_contents('data5.csv') .
file_get_contents('userdata.csv')
);
Note that this loads the entire files into PHP memory though. So, if they are big, you may get memory_limit issues.
If you want to just concatenate the two files you can do this easily with executing a shell script assuming you are on unix like os:
exec("cat data5.csv > final_data.csv && cat userdata.csv >> final_data.csv");
ob_start();
$dir1 = "csv/2014-01/";
$dir = $_REQUEST['folder_name'];
$totalfiles = count(glob($dir."/*",GLOB_BRACE));
echo "Total files in folder = ".$totalfiles;
if ($opend = opendir($dir)){
$i =0; $final_array_export= array();
$fil_csv =end(explode('/',$dir));
$file_name = 'download/'.$fil_csv.'.csv';
$file_cre = fopen($file_name,"w");
$headers = array("header1","header2");
fputcsv($file_cre,$headers);
while (($file = readdir($opend)) !== false){
$filename = $dir.'/'.$file;
$files = fopen($filename,"r");
if($files){
$fullarray = fgetcsv($files);
$head=array();
if(count($fullarray) >0){
foreach($fullarray as $headers){
$head[] = $headers;
}
}
while($data = fgetcsv($files,0,",")){
if(count($data) >0 && count($head) >0){
$array_combine = array_combine($head,$data);
}
fputcsv($file_cre,$array_combine);
}
}
}
fclose($file_cre);
header("Content-Type: application/force-download");
header("Content-type: application/csv");
header('Content-Description: File Download');
header('Content-Disposition: attachment; filename=' . $file_name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-length: ' . filesize($file_name));
ob_clean();
flush();
readfile($file_name);
}