I am having a problem with my webpage. I am building a report tool for downloading data as .csv - I have a php skript which aggregates the data and builds a csv from it. The skript is invoked with the exec() command, detailed code is below. The skript itself uses file_put_contents() to generate the file, which is then stored in my /tmp/ folder until its downloaded (I am working in a dockerized environment and our filter rules delete the file at the next request, but I could store the file permanently somewhere else if that would be neccessary). I am then checking if the file is present with file_exists() and proceed to invoke my download function. In Firefox I get the desired result, a file with the correct content of only the csv data.
My main Problem is: When I download the csv in Chrome I get the csv data followed by the html source of my page - so starting with <!doctype html> in the first line after the csv data, then <html lang="de">in the next line of te csv and so on..
Let me show you some code:
In my skript:
private function writeToFile($csv)
{
$fileName = '/path/to/file' '.csv';
echo "\n" . 'Write file to ' . $fileName . "\n";
file_put_contents($fileName, $csv);
}
In my page class:
$filePath = '/path/to/finished/csv/'
exec('php ' . $skriptPath . $skriptParams);
if (file_exists($filePath)) {
$this->downloadCsv($filePath);
} else {
$pageModel->addMessage(
new ErrorMessage('Error Text')
);
}
My download function in the same class:
private function downloadCsv($filePath)
{
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
The shown above is working in Firefox, but not in Chrome. I already tried to clear the output buffer with ob_clean() or send and disable it with ob_end_flush() but nothing worked for Chrome.
I also tried something like this in my download function:
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
$fp =fopen($filePath, 'rw');
fpassthru($fp);
fclose($fp);
This produces the same results in Firefox and Chrome - I get the csv data followed by the html sourcecode mixed into the same file.
I am working within a Symfony framework if that could be from help, I saw there are some helper functions for file downloads but I so far I could not use them with success..
Until now my target is only to get the download working in Chrome to have a working mvp which can go into production - it is supposed to be for internal use only, so I don't have to care about IE or some other abominations because our staff is told to use a normal browser... But when someone sees flaws in the general concept feel free to tell me!
Thanks in advance :)
So I managed to get it working, I was on the wrong track with the output buffer, but a simple exit()after my readfile()was enough to stop parts of the html ending up in the csv file.
Code:
private function downloadCsv($filePath)
{
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
}
Related
I am developing a very humble web app which routes all the requests to get an audio file toward a third party server, where the actual files are stored.
In order to do this, I am using the following statement in my PHP code:
echo file_get_contents('https://3rdpartyserver.com/' . $filename);
By testing it, it seems to work properly only for text files. While trying to get an .mp3 file, instead, its content as text is actually displayed (instead of the default HTML audio player, which is displayed if I connect directly to the third party server).
I have also tried to add some headers to the response:
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
But the resulting behavior is still not what I am looking for.
Might you please suggest me how to solve this issue?
You need to set the Content-Type to audio/mpeg, then write the file to the output buffer.
header("Content-Type: audio/mpeg");
header('Content-Disposition: attachment; filename=' . $filename);
readfile('https://3rdpartyserver.com/' . $filename);
exit;
I'm at a bit of a loss as to why this folder is not being found. I have a script that, after searching a database to find the $filename of someone's purchase based on a stored random code, should simply return their file. My code looks like this (including the trailing end of the db query):
$stmt_2 -> bind_result($filename);
$stmt_2 -> fetch();
$stmt_2 -> close();
// For .zip files
$filepath='/media-files/Label/' . $filename;
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
if (!is_file($filepath)) {
header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
echo 'File not found.';
} else if (!is_readable($filepath)) {
header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
echo 'File not readable.';
} else {
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
}
}
When I run this code, I receive "File not found." so !is_file($filepath) is where it is getting tripped up -- However, the path is correct and the zip is definitely there, so I'm not sure what is wrong here.
In terms of debugging, I've tried removing the checks, going directly to the headers and readfile, which returns an empty zip folder. What does work is if I navigate directly to the file by URL...
UPDATE
The file path issue has been fixed, but I am still not able to download the file. In all attempts I get either ERR_INVALID_RESPONSE or if I try to brute force download the file, it returns an empty file. I tried using these headers with no success:
header_remove();
ob_end_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
ob_end_flush();
exit;
They are large audio files, which appears to be causing the issue...
You have two types of pathes:
(a) The path of an URL. You have a web-adress which defines the root of your webpage.
e.g. https://www.stackoverflow.com is the start of the site. If you adress /questions at this site you always have the path https://www.stackoverflow.com/questions
(b) The path of the drive where the webpage is located. It is the filesystem-root.
e.g. /home/httpd/html/MyWebPage/questions
If you try to use /questions in (b) it will fail because you need the whole path.
So, this said you need to know where '/media-files/Label/'.$filename is located. It seems to me that /media-files is not at root-level of your filesystem (b).
Maybe it is at the web-root but this is not enough for your system to find the file. Therefore you need something like this:
'/root/httpd/MyWebPage/media-files/Label/'.$filename
Nico Haase was absolutely correct, this is an issue with misunderstanding of paths. Here is a link to an article that should clear things up:
https://phpdelusions.net/articles/paths
Currently your script is trying to find the file in:
/media-files/Label/file.zip
not:
/var/www/myproject/media-files/Label/file.zip
The linked article should provide you with all the neccesary information.
TLDR;
use:
$filepath=$_SERVER['DOCUMENT_ROOT'].'/media-files/Label/' . $filename;
UPDATE
With the file size issue it might be that PHP runs out of allowed memory when trying to load the whole file. We could try something like:
flush();
$file = fopen($filepath, "r");
while(!feof($file)) {
// send the current file part to the browser
print fread($file, round(10 * 1024));
// flush the content to the browser
flush();
}
fclose($file);
There are some issues with flush() but it's a good shot I think. You can have a read on: https://www.php.net/manual/en/function.flush
Other then that there is always the possibility to split the file into smaller chunks.
I have some ebooks on my server, that I want people to be able to download. I uploaded them and when I download them via my ftp tool then everything is perfect. when I use my script for the user to download it, then I get the following error in calibre:
MobiError: Unknown book type: '\x00\x00\x00BOOKM'
my script that handles the output of the file is as follows:
$file_url = ABSPATH . $file['file'];
$basename = $story->post_title . $subtitle . '.' . $_POST['type'];
$filename = basename(mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $basename));
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
readfile($file_url);
die();
Then all mobi readers I got say, that there is a problem with the file. I don't know what is going wrong. Also when I open the files in a text editor they are both different type. The one from my php script looks as follows:
the one that works from my ftp tool looks like this:
Anyone who can help me to find what I am doing wrong? The .epub files by the way are no problem with my script.
I solved this problem by outputting the file as follows:
ob_clean();
flush();
readfile($path);
exit;
So, I've followed a lot of posts here on StackOverflow still can't work out why my code doesn't work.
I want to be able to open a .pdf file outside the web root, so I've tried this code:
<?php
$file = '/user/Desktop/exemplo.pdf';
echo $file.'<br>';
$filename = 'test.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
#readfile($file);
?>
Problem is I always get the same error:
pdf this file cannot be correctly displayed
I've decided to try several browsers: firefox, chrome, opera and finally internet explorer which suprinsingly said something the others didn't:
file does not start with '%pdf-'Local\EWH-696-6
So does someone know what I need to configure in my code to open pdf's? Or to have them start with the code above (hardcoding it didn't fix it).
EDIT: tried removing the echo and still had the same error.
On my page, people can choose to either view a pdf-file (on screen) or to download it. (to view it later on when they're offline)
When users choose to download, the code is executed once. I am keeping track of this with a counter and it increments by 1 for each download. So, this option is working fine and can be seen in the if-block below.
When users choose to view the file, the pdf file is displayed - so that's OK - but the counter increments by 2 for each view. This code is run from the else-block below.
I also checked the "Yii trace" and it is really going through all of it twice, but only when viewing the file...
if ($mode==Library::DOWNLOAD_FILE){
//DOWNLOAD
Yii::app()->getRequest()->sendFile($fileName, #file_get_contents( $rgFiles[0] ) );
Yii::app()->end();
}
else {
//VIEW
// Set up PDF headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $rgFiles[0] . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($rgFiles[0]));
header('Accept-Ranges: bytes');
// Render the file
readfile($rgFiles[0]);
Yii::app()->end();
}
}
I tried a few other options, just to see how it would cause this to run twice:
When removing the "PDF headers" from the code above, the counter is
incremented by 1, but I obviously only get garbage on the screen...
If I get rid off the readfile command, the counter is also incremented by 1,
but the browser won't render the pdf (because it is not getting the data without this line)...
So, it's only when going through the else-block that all of it (Yii request) is executed twice...
Thanks in advance for any suggestions...
I think that is because with the sendFile() method you open the file actually just once, and in the else branch you really open it twice.
In the if branch you open the file once with the file_get_contents() and pass the file as a string to the sendFile() method and then it counts the size of this string, outputs headers, etc: http://www.yiiframework.com/doc/api/1.1/CHttpRequest#sendFile-detail
In the else branch you open the file first with the filesize() and then also with the readfile() method.
I think you could solve this problem by rewriting the else branch similar to the sendFile() method:
Basically read in the file with file_get_contents() into a string, and then count the length of this string with mb_strlen(). After you output the headers, just echo the content of the file without reopening it.
You could even copy-paste the whole sendFile() method into the else branch, just change the "attachment" to "inline" in the line (or replace this whole if/else statement with the sendFile method and just change the attachment/inline option to download or view, an even more elegant way would be overriding this method and extending with another parameter, to view or download the given file) :
header("Content-Disposition: attachment; filename=\"$fileName\"");
So I think something like this would be a solution:
// open the file just once
$contents = file_get_contents(rgFiles[0]);
if ($mode==Library::DOWNLOAD_FILE){
//DOWNLOAD
// pass the contents of file to the sendFile method
Yii::app()->getRequest()->sendFile($fileName, $contents);
} else {
//VIEW
// calculate length of file.
// Note: the sendFile() method uses some more magic to calculate length if the $_SERVER['HTTP_RANGE'] exists, you should check it out if this does not work.
$fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
// Set up PDF headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $rgFiles[0] . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $fileSize);
header('Accept-Ranges: bytes');
// output the file
echo $contents;
}
Yii::app()->end();
I hope this solves your problem, and my explanations are understandable.