So here's a question. Can a php script detect how it is being called? For example if it is called through <img> it will return an image, or if it is being called through <video> it will return video, or if it is called through <audio> it will return audio, or if it is called directly by typing in http://www.example.com/callme.php it will return some text.
The content from this callme.php would be provided through the following method:
header("Content-Disposition: attachment; "
.sprintf('filename="%s"; ', rawurlencode($_REQUEST['F']))
.sprintf("filename*=utf-8''%s", rawurlencode($_REQUEST['F'])));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
flush(); // this doesn't really matter.
$fp = fopen($file, "r") or die("DEAD");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
No this is not possible, at least not without some additional parameters in the URL.
Consider the following HTML
<img src="/callme.php?target=img" />
With the following PHP:
if ($_GET('target') == 'img') { ... }
Related
I have a pdf generated invoice witch i like to display inline in the browser:
link is for example: guest/view/invoice/vqhH8sujcOrpg0t2nF4WQExDLKXmYTNe
No extension.
the below code gets a failed to load PDF document when i change it to attachment it works but give a download while i like to display it inline.
$file = site_url('guest/view/generate_invoice_pdf/' . $invoice_url_key);
$filename = 'factuur.pdf';
header("Content-type: application/pdf");
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
echo $file;
Sorry i though i did a thorough search but i din't solution is this:
Orginal from: Chrome has "Failed to load PDF document" error message on inline PDFs
I've been wrestling with this same issue. This is as close as I got to consistent results across browsers. I think that the reason you could be having problems is if some PDF's are too large for readfile() to handle correctly. Try this:
$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 have the following download.php script to download a file, which works great:
<?php
header("Content-Type: application/octet-stream");
$file = $_GET["file"];
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
?>
What I want to achieve is to hide the URL where this file is located, so that when the user clicks a link such as <a target="_blank" href="http://domain.com/files/download.php?file=filename.pdf">Download file</a>, a new tab opens up with no URL and starts downloding the file. What is actually happening is the new tab opens and the file download starts but the URL bar is displaying http://domain.com/files/download.php?file=filename.pdf.
If this cannot be done with php, how can I achieve this? I have seen several downloads where the URL is not shown, so I know this is somehow possible.
EDIT: Here is the reason I want to do this: We will send a html mailing with a link to the file download, and the website where this file download is hosted is not the website from the company which sends the mail.
As always, thank you very much.
A typical way doing this, is to place the files you want to provide for download outside your docroot.
Your download script should know about this place and has to process the requested filename considering this.
For example:
path/in/your/system/docroot/download.php
and
path/in/your/system/files/filename.pdf
If someone is requesting download.php?file=filename.pdf your script has to look up in path/in/your/system/files/ for this file and has to handle it.
You can create a new window with iframe content to that URL.
var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));
win.document.body.innerHTML = "<iframe src='YOUR URL'></iframe>";
If you remove the target="_blank" no new tab will be opened and the file will just be downloaded.
In the end, it's not possible because the user can open Google Inspector and check the Network tab.
Edit: If that's the case, you would use JavaScript:
Edit 2: In case the popup is blocked by the browser or addon, use a fallback:
Edit 3: In case JS is disabled:
<head><meta http-equiv="refresh" content="5;http://domain.com/files/download.php?file=filename.pdf">
<script>
var win = window.open("http://domain.com/files/download.php?file=filename.pdf");
if (!win) {
window.location = "http://domain.com/files/download.php?file=filename.pdf";
}
</script>
</head>
Edit 4: If you don't want the user to see the domain of the user site at all, get your PHP script to download the file and then output that to the user:
header("Content-Type: application/octet-stream");
$file = $_GET["file"];
$file = 'http://otherdomain.com/location/' . $file; // This line should suffice for all that you're trying to do
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush();
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush();
}
fclose($fp);
Submit the form as POST and use $_REQUEST to get the file:
$file = $_REQUEST["file"];
I have a script that outputs an image.
Works fine
include('../myfolder/myImageScript.php'); // outputs image on page
Fails
echo file_get_contents('../myfolder/myImageScript.php'); // nothing displayed
I think this fails because in php a script, in my case myImageScript.php, isn't executed when called via the file_get_contents() function, but is when called using a include() the script is executed.
I am struggling to get a zip function to work due to the empty output of file_get_contents().
the file i'm trying to call via file_get_contents() is:
myImageScript.php
$imgstr = "data:image/jpeg;base64,/9j/........... rest of string";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}
// Decode the data
$content = base64_decode($matches[2]);
// Output the correct HTTP headers
header('Content-Type: '.$matches[1]);
//header("Content-Type: image/jpeg"); // tried this made no difference
// Output the actual image data
echo $content;
Any help would be greatly appreciated.
Something like this should work, BUT you need to enable ZipArchive http://php.net/manual/en/class.ziparchive.php (should not be a problem)
<?php
$imgstr = "data:image/gif;base64,R0lGODlhyAAiALMAAFONvX2pzbPN4p6/2tTi7mibxYiw0d/q86nG3r7U5l2UwZO31unx98nb6nOiyf///yH5BAUUAA8ALAAAAADIACIAAAT/8MlJq7046827/2AojmRpnmiqriwGvG/Qjklg28es73wHxz0P4gcgBI9IHVGWzAx/xqZ0KlpSLU9Y9MrtVqzeBwFBJjPCaC44zW4HD4TzZI0h2OUjON7EsMd1fXcrfnsfgYUSeoYLPwoLZ3QTDAgORAoGWxQHNzYSBAY/BQ0XNZw5mgMBRACOpxSpnLE3qKqWC64hk5WNmBebnA8MjC8KFAygMAUCErA2CZoKq6wHkQ8C0dIxhQRED8OrC1hEmQ+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+uOAkBFDDA2wxABkPJiMe8+OUaECVNLMZUJI755xtoHmwXnoNuugUQp4bGLzf0dvrriy2wsAMD4A377YJjSgDfD0QAADs=";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
$content = base64_decode($matches[2]);
$zip = new ZipArchive;
$filename = tempnam("/tmp", "testmeZip");
$res = $zip->open($filename, ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.gif', $content);//you can use $matches to figure out extension
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
header("Pragma: public");
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=\"test.zip\"");
header("Content-Transfer-Encoding: binary");
// make sure the file size isn't cached
clearstatcache();
header("Content-Length: ".filesize($filename));
// output the file
readfile($filename);
Here, I have been trying to convert the HTML file to PDF using PHP and download it when user clicks on 'download' button. I am able to convert HTML to PDF but I am not able to download it, instead some erroneous file($file) gets downloaded when I try to open this PHP page.
I have referred download file using PHP and SO question Using php to force download a pdf but did not help me.
Here is my PHP code:
<?php
function download_pdf()
{
require('html2pdf/html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen("demo.html","r");
$strContent = fread($fp, filesize("demo.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
}
function download()
{
download_pdf();
// Define the path to file,you want to make it downloadable
$file = ‘sample.pdf’;
if(!$file)
{
// File doesn’t exist, output will show error
die(" file not found");
}
else
{
// Set headers
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=$file');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
// Read the file from disk
readfile($file);
}
}
?>
<input type="button" name="download" value="Download as PDF" style=" position:absolute; top:520px; left:600px;" onclick="<?php download(); ?>"/>
Change your PHP code to this and make some changes accordingly, especially setting the path of your file. Reference link: download file.
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// Download here
?>
You need double quotes here:
header("Content-Disposition: attachment; filename=$file");
The code below forces browser to fire a prompt to save/open file (https://kb.wisc.edu/images/group27/13334/open-prompt.PNG) even if it's a image or pdf file.
I want images to be opened as usual, pdf files to be displayed in browser. And of course other files that are not supported by browser like zip, rar, doc, xls etc will fire a save file dialog.
Edit:
My intention is not to block client to save the file of course they can save it that's impossible. I want to serve let say images as PHP files like main.php?file=randomcode (which is stored in database) but not as /images/somefilename.jpg . My code forces client to download it but I want to display it.
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename . "." . $fileinfo["file_extension"] . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file));
$fp = fopen($file, "r");
if ($fp) {
while (!feof($fp)) {
$cur_data = fread($fp, 1024);
echo $cur_data;
}
} else {
echo "Error: Could not the read file.";
}
Ultimately it's up to the client what to do with the content it receives. One thing you can do is get rid of the Content-disposition header:
header("Content-Disposition: attachment; filename=\"" . $filename . "." . $fileinfo["file_extension"] . "\";");
(Or at least get rid of it conditionally, depending on specific factors about the file.) What this header does is tell the client that the content being returned is a "file" (you even provide a suggested name for the file) and should be treated as such. HTTP has no native concept of "files" so this header exists specifically to identify something as a "file."
By not supplying that header, you're not suggesting to the client that the content is a file. The client may still infer that it's a file and treat it as such (which you can't control), but from your end all you'd be doing is returning the content itself.
Well, apparently you know the file extension so you could do:
if(in_array($fileinfo["file_extension"], array('jpg', 'png', 'gif')) {
// set header for viewing the image
$mime_type = $fileinfo["file_extension"];
if($mime_type == 'jpg') {
$mime_type = 'jpeg';
}
header('Content-Type: image/' . $mime_type);
}
else {
// set headers for downloading the file
}
if the content type is set to octate stream then it will defenetly transfer the file means user will force download it. you have to set content type accordingly to open it in browser
for example if type is image then
header("Content-Type: image/jpg");
header("Content-Type: image/png");
etc.
and if its image or pdf then remove Content-Disposition: header