I am using phpdocx to create a word document. It is a valid word document when I look at it on the server. However, when I try to download it, it says that the file cannot be opened because there are problems with the file. Word is able to recover the document, but it clients will complain about an invalid word document. Here is the code I use to download the file:
function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
set_time_limit(0);
$defaultchunksize = 1024*1024;
$chunksize = $defaultchunksize;
$buffer = '';
$cnt = 0;
$remotereadfile = false;
if (preg_match('/[a-zA-Z]+:\/\//', $filename))
$remotereadfile = true;
$handle = #fopen($filename, 'rb');
if ($handle === false) {
return false;
}
stream_set_timeout($handle, $timeout);
if ($seek != 0 && !$remotereadfile)
fseek($handle, $seek);
while (!feof($handle)) {
if ($remotereadfile && $seek != 0 && $cnt+$chunksize > $seek)
$chunksize = $seek-$cnt;
else
$chunksize = $defaultchunksize;
$buffer = #fread($handle, $chunksize);
if ($retbytes || ($remotereadfile && $seek != 0)) {
$cnt += strlen($buffer);
}
if (!$remotereadfile || ($remotereadfile && $cnt > $seek))
echo $buffer;
ob_flush();
flush();
}
$info = stream_get_meta_data($handle);
$status = fclose($handle);
if ($info['timed_out'])
return false;
if ($retbytes && $status) {
return $cnt;
}
return $status;
}
Thanks!
Related
$find = '.5010.';
$directory_with_files = './'.date('m-d-Y');
$dh = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
if(in_array($filename, array('.', '..')) || is_dir($filename))
continue;
$files[] = $filename;}
foreach($files as $file){
//find only 5010 files
if(stripos($file, $find) !== false){
// open the 5010 file
$handle = fopen(date('m-d-Y').'/'.$file, "r");
$file_content = file_get_contents(date('m-d-Y').'/'.$file);
$handle2 = fopen(date('m-d-Y').'/'.$file, "r");
$file_content2 = file_get_contents(date('m-d-Y').'/'.$file);
if ($handle) {
$header = '';
$name = '';
$footer = '';
$payor_blocks = array();
// determine if file has more than one payor
$payor_count = substr_count($file_content, 'N1*PR*');
//if the file has more than one payor
if($payor_count > 1) {
//read the file line by line
$header_end = false;
$block_start = false;
$count = 1;
if($handle2){
$line_number = 0;
$line_stop= array();
while (($line1 = fgets($handle2)) !== false) {
$line_number++;
if(strpos($line1, 'CAS') !==false){
$line_stop[] = $line_number;}}
$footer_line = count($line_stop)-2;
$footer_line = $line_stop[$footer_line];
$line_number = 0; }
//look for occurances of CAS and what line each on is on
while (($line = fgets($handle)) !== false) {
$line_number++;
//look for the first payor block
if(strpos($line, 'N1*PR*') !== false || $block_start) {
$header_end = true; $block_start = true;
if(strpos($line, 'N1*PR*') !== false) {
$count++;
}
//see if the block finished
if($line_number == $footer_line) {
$block_start = false;
$payor_blocks[$count] .= $line;
$count++; }
$payor_blocks[$count] .= $line;}
else {
if($header_end) {
$footer .= $line."\n"; }
else {
$header .= $line."\n";}}
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber);
if($refnumber != '')
{
$refnumber = '_'.$refnumber.'_';
$filerenamed = str_replace($find, $refnumber,$file);
copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
}
echo $refnumber . "\n";
}
}
//get payor blocks and create a file foreach payor
$new_files = array();
foreach($payor_blocks as $block) {
$filename = date('m-d-Y').'/'.$file . "_" . $count;
$count++;
$new_files[] = array(
'name' => $filename,
'content' => $header."\n".$block."\n".$footer
);
}
foreach($new_files as $new_file) {
$myfile = fopen($new_file['name'], "w");
fwrite($myfile, $new_file['content']);
fclose($myfile);
}
}
else{
while (($line = fgets($handle)) !== false)
{
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber);
if($refnumber != '')
{
$refnumber = '_'.$refnumber.'_';
$filerenamed = str_replace($find, $refnumber,$file);
copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
}
echo $refnumber . "\n";
}
}
}
}
}
// DONE - close the file
fclose($handle);
}
foreach($files as $fiftyfile){
if(stripos($fiftyfile, $find) !== false){
$handle3 = fopen(date('m-d-Y').'/'.$fiftyfile, "r");
$file_content3 = file_get_contents(date('m-d-Y').'/'.$fiftyfile);
if ($handle3) {
if(unlink('./'.date('m-d-Y').'/'.$fiftyfile))
{
echo "file named $fiftyfile has been deleted successfully";
}
else
{
echo "file is not deleted";
}
}
}
}
I have a few files in my directory with filenames that contain "3256.5010.548674.23a" In this code it opens the file and searches if there is more than one "N1*PR*" and if there is to split them into separate files. Lastly to change ".5010." to the REF number which is something like "8743" . Then it deletes all the files with ".5010." And combines the rest in one document. It works fine however, when I first run it it splits and renames, but only deletes the first files not all the ".5010." (not the ones that were split), which then when I run it again after that, it deletes everything but renames the old ones, since it goes through the "else statement" that also does the renaming. How could I solve the issue with the delete?
All i want is to open a rsyslog file with fopen() take the first 3 lines set a variable with the last of this 3 lines. Then take the other 3 lines e.t.c.
$path_file = variable_get('$path');
$file = fopen($path_file, 'r');
for($i=0;$i<3;$i++) {
$line = fgets($file);
$line = variable_set($line);
}
fclose($file);
Use file() instead (reads everything in as an array)
Try this:
$file = file('$path');
for($x = 0; $x < count($file); $x = $x + 3)
{
if(isset($file[$x]) && isset($file[$x +1]) && isset($file[$x + 2])
{
//do something with the values.
}
}
function readFileStartingAtLineNumber($x)
{
$file = file('$path');
if(isset($file[$x]) && isset($file[$x +1]) && isset($file[$x + 2])
{
//do something with the values.
}
}
function getLog($path, $numberOfLines, $lastIndex) {
$file = fopen($path, 'r');
if (!$file) {
print 'error opening file';
}
else {
$data = '';
$i = -1;
while(($line = fgets($file)) !== FALSE) {
if(++$i < $lastIndex) continue;
if($numberOfLines-- == 0) break;
$data .= $line;
}
fclose($file);
if ($data === '') {
print 'EOF reached without getting data';
}
}
return $i;
}
I have tried to save attachment but i couldn't download attachment with this code .it create a folder for downloading file. any one? How to save a attachment on email in php?
thanks in advance
$struct = imap_fetchstructure($mbox,$msgno);
$contentParts = count($struct->parts);
if ($contentParts >= 2)
{
for ($i=2;$i<=$contentParts;$i++)
{
$att[$i-2] = imap_bodystruct($mbox,$msgno,$i);
}
for ($k=0;$k<count($att);$k++)
{
if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII")
{
if ($att[$k]->parameters[1]->value != "")
{
$selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
}
}
elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1")
{
$selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
}
}
}
//print_r($att);
if (count($selectBoxDisplay) > 0)
{
for ($j=0;$j<sizeof($selectBoxDisplay);$j++)
{
$strFileName = $att[$j]->parameters[0]->value;
$strFileType = strrev(substr(strrev($strFileName),0,4));
$fileContent = imap_fetchbody($mbox,$msgno,$j+2);
$ret = downloadFile($strFileType,$strFileName,$fileContent);
$selectBoxDisplay[$j] = str_replace($search,'',$selectBoxDisplay[$j]);
$filenametmp = $selectBoxDisplay[$j];
$handle = fopen($filenametmp, "w+");
fwrite($handle, $ret);
fclose($handle);
//chmod($filenametmp, 777);
}
}
I have created a website which allows the user to zip multiple files from remote sites, combine them into a zip file, then download them. This part is working very well.
The problems I am having:
1) The zip takes too long to generate when combining multiple files
2) I cannot set the zip files name to be $name
This is what I have:
<?php
$files = unserialize($_POST['filesend']);
$name = $_POST['name'];
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach($files as $file){
$download_file = file_get_contents($file);
$zip->addFromString(basename($file),$download_file);
}
$zip->close();
function downloadfile ($file, $contenttype = 'application/octet-stream') {
#error_reporting(0);
if (!file_exists($file)) {
header("HTTP/1.1 404 Not Found");
exit;
}
if (isset($_SERVER['HTTP_RANGE'])) $range = $_SERVER['HTTP_RANGE'];
else if ($apache = apache_request_headers()) {
$headers = array();
foreach ($apache as $header => $val) $headers[strtolower($header)] = $val;
if (isset($headers['range'])) $range = $headers['range'];
else $range = FALSE;
} else $range = FALSE;
$filesize = filesize($file);
if ($range) {
$partial = true;
list($param,$range) = explode('=',$range);
if (strtolower(trim($param)) != 'bytes') {
header("HTTP/1.1 400 Invalid Request");
exit;
}
$range = explode(',',$range);
$range = explode('-',$range[0]);
if (count($range) != 2) {
header("HTTP/1.1 400 Invalid Request");
exit;
}
if ($range[0] === '') {
$end = $filesize - 1;
$start = $end - intval($range[0]);
} else if ($range[1] === '') {
$start = intval($range[0]);
$end = $filesize - 1;
} else {
$start = intval($range[0]);
$end = intval($range[1]);
if ($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1)))) $partial = false;
}
$length = $end - $start + 1;
} else $partial = false;
header("Content-Type: $contenttype");
header("Content-Length: $filesize");
header("Content-Disposition: attachment; filename= $name .zip");
header('Accept-Ranges: bytes');
if ($partial) {
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes $start-$end/$filesize");
if (!$fp = fopen($file, 'r')) {
header("HTTP/1.1 500 Internal Server Error");
exit;
}
if ($start) fseek($fp,$start);
while ($length) {
$read = ($length > 8192) ? 8192 : $length;
$length -= $read;
print(fread($fp,$read));
}
fclose($fp);
} else readfile($file);
exit;
}
downloadfile ($tmp_file, $contenttype = 'application/octet-stream');
?>
Sample input:
$files = array("http://img3.wikia.nocookie.net/__cb20100520131746/logopedia/images/5/5c/Google_logo.png","http://www.logobird.com/wp-content/uploads/2011/03/new-google-chrome-logo.jpg","http://steve-lovelace.com/wordpress/wp-content/uploads/2013/06/google-logo-in-chicago-font.png","http://fc08.deviantart.net/fs70/f/2013/111/d/6/applejack_google_logo__install_guide___by_thepatrollpl-d62gui3.png","http://www.sfweekly.com/binary/fb4a/go.jpg","https://www.google.com/logos/doodles/2014/world-cup-2014-16-5975619640754176.3-hp.gif");
$name = "Google Logo's 33";
To address your two issues:
1) Slow file processing speed.
I don't know that you can help that. It is what it is.
2) Saving the name.
I have formatted this into a class, just to keep jobs separate. I find a class works better in a situation like this because it's easier to read. That being said, because each method may use the protected $filename you should copy everything here instead of breaking this code out an mixing your procedural with this class:
class DownloadFiles
{
protected $filename;
protected $Zipper;
public function Initialize($filename = false)
{
// Set the file name in the construct
$this->filename = ($filename != false)? $filename:"file".date("YmdHis");
// New ZipArchive instance
$this->Zipper = new ZipArchive();
// Drop the filename here
$this->Zipper->open($this->filename, ZipArchive::CREATE);
// Return the method for optional chaining.
return $this;
}
public function AddFiles($array = array())
{
if(!isset($this->Zipper))
return $this;
// This is just if you wanted to also use a string
// separated by commas, it will convert to array
if(!is_array($array) && strpos($array,",") !== false)
$array = explode(",",$array);
// Loop through files (as you have it already)
if(is_array($array) && !empty($array)) {
foreach($array as $url) {
// Add Contents (as you have it)
$this->Zipper->addFromString(basename($url),file_get_contents($url));
}
}
// Close zip file
$this->Zipper->close();
// Return for method chaining
return $this;
}
public function DownloadZip($contenttype = 'application/octet-stream')
{
if(!isset($this->filename))
return $this;
// Nothing really changes in this function except
// you don't need the name as an option in this function
error_reporting(0);
if (!file_exists($this->filename)) {
header("HTTP/1.1 404 Not Found");
exit;
}
$range = false;
if(isset($_SERVER['HTTP_RANGE']))
$range = $_SERVER['HTTP_RANGE'];
elseif($apache = apache_request_headers()) {
$headers = array();
foreach ($apache as $header => $val)
$headers[strtolower($header)] = $val;
$range = (isset($headers['range']))? $headers['range']:false;
}
$filesize = filesize($this->filename);
$partial = false;
if($range) {
$partial = true;
list($param,$range) = explode('=',$range);
if(strtolower(trim($param)) != 'bytes') {
header("HTTP/1.1 400 Invalid Request");
exit;
}
$range = explode(',',$range);
$range = explode('-',$range[0]);
if(count($range) != 2) {
header("HTTP/1.1 400 Invalid Request");
exit;
}
if($range[0] === '') {
$end = $filesize - 1;
$start = $end - intval($range[0]);
}
elseif($range[1] === '') {
$start = intval($range[0]);
$end = $filesize - 1;
}
else {
$start = intval($range[0]);
$end = intval($range[1]);
if($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1))))
$partial = false;
}
$length = $end - $start + 1;
}
header("Content-Type: $contenttype");
header("Content-Length: $filesize");
header('Content-Disposition: attachment; filename='.$this->filename.'.zip');
header('Accept-Ranges: bytes');
if($partial) {
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes $start-$end/$filesize");
if(!$fp = fopen($this->filename, 'r')) {
header("HTTP/1.1 500 Internal Server Error");
exit;
}
if($start)
fseek($fp,$start);
while($length) {
$read = ($length > 8192) ? 8192 : $length;
$length -= $read;
print(fread($fp,$read));
}
fclose($fp);
}
else
readfile($this->filename);
exit;
}
}
?>
To use:
$files[] = "http://img3.wikia.nocookie.net/__cb20100520131746/logopedia/images/5/5c/Google_logo.png";
$files[] = "http://www.logobird.com/wp-content/uploads/2011/03/new-google-chrome-logo.jpg";
$files[] = "http://steve-lovelace.com/wordpress/wp-content/uploads/2013/06/google-logo-in-chicago-font.png";
$files[] = "http://fc08.deviantart.net/fs70/f/2013/111/d/6/applejack_google_logo__install_guide___by_thepatrollpl-d62gui3.png";
$files[] = "http://www.sfweekly.com/binary/fb4a/go.jpg";
$files[] = "https://www.google.com/logos/doodles/2014/world-cup-2014-16-5975619640754176.3-hp.gif";
$name = "Google Logo's 33";
// Initialize
$ZDownload = new DownloadFiles();
// Run downloader
$ZDownload->Initialize($name)->AddFiles($files)->DownloadZip();
I have a 22M docx file and want to encode it using base64_encode() function in php. But It always returns NULL value after running this function. Is there any limit file size or condition for this function. My code:
$handle = fopen($fullpathfile, "rb");
$imagestr = base64_encode(fread($handle, filesize($fullpathfile)));
fclose($handle);
Try this code
$fh = fopen($fullpathfile, 'rb');
$cache = '';
$eof = false;
while (1) {
if (!$eof) {
if (!feof($fh)) {
$row = fgets($fh, 4096);
} else {
$row = '';
$eof = true;
}
}
if ($cache !== '')
$row = $cache.$row;
elseif ($eof)
break;
$b64 = base64_encode($row);
$put = '';
if (strlen($b64) < 76) {
if ($eof) {
$put = $b64."\n";
$cache = '';
} else {
$cache = $row;
}
} elseif (strlen($b64) > 76) {
do {
$put .= substr($b64, 0, 76)."\n";
$b64 = substr($b64, 76);
} while (strlen($b64) > 76);
$cache = base64_decode($b64);
} else {
if (!$eof && $b64{75} == '=') {
$cache = $row;
} else {
$put = $b64."\n";
$cache = '';
}
}
if ($put !== '') {
echo $put;
}
}
fclose($fh);