I have the following code in a "function" file [2] in my project. It can be called for multiple types of reports in my project. The $name comes from the reports pages using the $thePDFFileName [1]:
[1] $pdf->Output($thePDFFileName);
...
[2] $f=fopen($name,'wb');
if(!$f)
{
$this->Error('Unable to create output file: '.$name);
}
fwrite($f,$this->buffer,strlen($this->buffer));
fclose($f);
...
[1] FunctionSendFile::sendPDFFile($thePDFFileName );
Example: $thePDFFileName = tmp/[Filename]_19-11-2013.pdf
What's strange is before it was working for all my reports, now all of a sudden it always returns null (empty) for $f=fopen($name,'wb'); and I have no idea why. I tried removing the if condition to force the file being created, and it makes a pdf file of 0 bytes (I'm assuming because fopen() fails).
Has anyone seen this happen before and know how to fix it? I'm not sure what i've done to make all the pdf files stop working...
NOTE: I am trying to create these files and save them in a certain location. I'm not trying to find and open files that already exist!
Related
I currently have a PHP script that exports data about an invoice in a CSV file, based on the invoice's ID number. The file is dynamically generated and is not saved on the server. To be more specific, I am echoing rows, and setting the following headers so that the echos appear in a file attachment:
header('Content-type: text/plain');
header("Content-Disposition: attachment; filename=INV${id}.csv");
The way I can call the script is using:
my_script.php?id=123
However now, I need to write a script that grabs all invoices of a given day, get their corresponding CSV files, and download them to the client as a ZIP file. Can I do that using my already existing script that outputs one file?
What I was thinking about is getting the list of all relevant invoice IDs from the database (say 123, 456 and 789), then looping over them and call my script for each of the IDs, like:
my_script.php?id=123 //then 456, then 789
and then save the file results into an array.
My attempt so far:
So far, I tried saving one resulting file as a variable as per this answer, but the variable remains empty (while the already existing script does return a non-empty file):
$file = getScriptOutput("my_script.php?id=123");
echo $file;
function getScriptOutput($path, $print = FALSE)
{
ob_start();
if( is_readable($path) && $path )
{
include $path;
}
else
{
return FALSE;
}
if( $print == FALSE )
return ob_get_clean();
else
echo ob_get_clean();
}
So, two questions here:
1 - How do I make an array of files, where each one is a file result (attachment) of a PHP script?
2 - How do I combine all these dynamic files into one ZIP file in PHP?
Edit: The suggested duplicate does help for the zipping part, but I need to know how to get the file attachment of a PHP script (Is there a way without saving the file on the server, because of storage and security concerns?).
You could just save all your files in some location, then access them and put them into a zip file like this:
$zip = new ZipArchive;
if ($zip->open('test_new.zip', ZipArchive::CREATE) === TRUE)
{
// Add files to the zip file
$zip->addFile('test.txt');
$zip->addFile('test.pdf');
// All files are added, so close the zip file.
$zip->close();
}
Well, I rethought my plan, and I finally went for the following:
For each of the IDs:
Read the attachment of the http response coming from my_script.php?id=123 and saving it into a variable as per this answer (using cURL and setting CURLOPT_BINARYTRANSFER => TRUE)
Create a temporary file and writing in it the varaible's data (typical fopen and fwrite did the job)
Add the file to the ZIP archive, as per #DigitalJedi's answer
After sending the ZIP, delete the temporary file using unlink("filename.csv").
I have a .txt file located under some folder of my data files. Now I have created a long polling system (actually copied the code ) which is run by ajax.
Now the problem is that my php script is unable to fetch file modification time of the text file (it totally disregards the file).
Below I have both the original code of the author and my twerked code. The one of the author worked fine, but not mine.
Plz help.
The apache server is hosted on windows server
THe file path is absolutly correct and file exist.
Here's the section of my code which has error
while (true) {
//**The error occurs here**
$fileModifyTime = filectime($file);
if ($fileModifyTime === false) {
throw new Exception('Could not read last modification time');
}
// if the last modification time of the file is greater than the last update sent to the browser...
if ($fileModifyTime > $lastUpdate) {
setcookie('lastUpdate', $fileModifyTime);
require 'msgread.php';
// get file contents from last lines...
$fileRead = tailCustom($file, 8);
exit(json_encode([
'status' => true,
'time' => $fileModifyTime,
'content' => $fileRead
]));
}
// to clear cache
clearstatcache();
// to sleep
sleep(1);
}
here's the original code from where i copied
the author's original polling code
and here's my full code, just in case needed
My script which has error
I suspect that your problem is that file.txt does not exist. have you created it and ensured that it's in the current working directory of the script?
It's impossible to say more without seeing your actual code. If you select it and press Ctrl + K that will indent it all.
I am trying to move uploaded files to new location using SugarCRM's logic hook either after_save or before_save. But I am unable to do so. Kindly find my logic hook code:
class attachment
{
public function attachment(&$bean, $event, $arguments)
{
if(!empty($bean->filename_new))
{
$upload_dir = $GLOBALS['sugar_config']['upload_dir'];
$target_file = $upload_dir . basename($_FILES["filename_new_file"]["name"]);
if (move_uploaded_file($_FILES["filename_new_file"]["tmp_name"], $target_file))
{
$GLOBALS['log']->fatal("The file has been uploaded");
}
else
{
$GLOBALS['log']->fatal("Sorry, there was an error uploading your file.");
}
}
}
}
Here, when I print $_FILES, I am getting desired output:
Array
(
[name] => twitter.png
[type] => image/png
[tmp_name] => /tmp/php5wBmgK
[error] => 0
[size] => 203
)
Now I have seen many posts, where they mentioned solution for this is to make sure the correct file permission and file ownership. I tried that, but didn't work out.
Lastly, to remove the possibility of issue with file permission or file ownership, I made one file upload script and run that script outside of CRM and that time move_uploaded_file function worked as it should.
But when I try to achieve the same with the use of logic hook, I am unable to get desired output. Kindly guide me here.
If you are using UNIX please check Permission also.
Check this file Rootapp/include/upload_file.php you will get different function related to file .I use this to copy file.
And you want to change location of file where file saving then ,
If you look at your config.php file, you will see a line that looks like this.
'upload_dir' => 'upload/',
to copy a file i did like this,
$bean->file_mime_type = $result->file_mime_type;
$bean->filename = $result->filename;
require_once('include/upload_file.php');
$uploadFile = new UploadFile();
$upoad_atachment =
$uploadFile->duplicate_file($result->id, $bean->id)
IN logic hook after save when i get email with attachment i copy that attachment and insert that files into my custom module.
Every image have some id , the image name uploaded with that id, so find that id , for email that attachment information save into notes module, In your case you find in your module. then get that information in your result and copy that in other module.
I'm creating using PHP a file:
$file = fopen(__DIR__ . "/../folder/example_$array[nothing].txt", "w");
Problem is, that there are two files generated:
example_.txt
example_test.txt
I don't know, why there are created these two files. I just wanna have the example_test.txt, the other one is the undesirabled. I checked the directory using var_dump and the two files appear after the code above was executed. The function is also only one time called.
Does anyone know what can be the issue?
EDIT:
$array is read by a file and contains something like ["nothing" => "test", "something more" => "okay"].
I have a small number of image files and text files. They have the same file name with different extensions. I need to read the image files and for each image I need to read some (tool top) text from the corresponding text file. The problem is the file open inside the "foreach( glob("inserts/*.png")" loop fails. I have output the filename and the fopen works fine. I thought it may be you are unable to open two file concurrently in PHP but I could find nothing about it when I googled
foreach( glob("inserts/*.png" ) as $filename ) {
$path="public/xml/iweb/".$filename;
$insertpath=substr($filename, 0, -3)."txt";
$myfile = fopen($insertpath, "r");
$rec=fread($myfile,filesize($insertpath));
fclose($myfile);
$name=getInnerSubstring($rec,"-");
$HTML5.="<img class='insertimage' src='".$path."' title='".$name."' onclick='insertcomponent(\"".$insertpath."\")'>";
}
One day I hope I know enough to answer questions instead of just asking them. :(
There's no reason why you shouldn't be able to open multiple files and no reason the foreach should break anything that works. My hunch is that the path you're trying to open is wrong. I suggest either debugging the code to see the variables or add an echo to see their content. You should also check if fopen() and fread() don't return some false because they failed. Good luck :)