php how to serve file but NOT for download - php

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

Related

download image from another server url without saving in my server folder

I have problem in download image from url,
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
in this code file is saving in my server folder .but i needed without saving in my server it needs to be download to user.
set the correct header and echo it out instead of file_put_contents
$url = 'http://example.com/image.php';
header('Content-Disposition: attachment; filename:image.jpg');
echo file_get_contents($url);
Use application/octet-stream instead of image/jpg:
If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
— RFC 2616 – 19.5.1 Content-Disposition
EDIT
function forceDownloadQR($url, $width = 150, $height = 150) {
$url = urlencode($url);
$image = 'http://chart.apis.google.com/chart?chs='.$width.'x'.$height.'&cht=qr&chl='.$url;
$file = file_get_contents($image);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=qrcode.png");
header("Cache-Control: public");
header("Content-length: " . strlen($file)); // tells file size
header("Pragma: no-cache");
echo $file;
die;
}
forceDownloadQR('http://google.com');
if you want to download the file onto your webserver(and save it), just use copy()
copy($url, 'myfile.png');

try to download file and getting invalid file in response in core php

I download a file but it gives invalid file in return.
Here's my download_content.php
<?php
$filename = $_GET["filename"];
$buffer = file_get_contents($filename);
/* Force download dialog... */
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
/* Don't allow caching... */
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
/* Set data type, size and filename */
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($buffer));
header("Content-Disposition: attachment; filename=$filename");
/* Send our file... */
echo $buffer;
?>
download file link:
Download
$r['file'] contains the file name to be downloaded.
The complete path of the folder which contain the file is:
localhost/ja/gallery/downloads/poster/large/'.$r['file'].'
ja is the root folder in htdocs.
I don't know what the actual problem is, can anyone help me out please?
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
As said in the other question, this way looks better:
$filename = $_GET["filename"];
// Validate the filename (You so don't want people to be able to download
// EVERYTHING from your site...)
// For example let's say that you hold all your files in a "download" directory
// in your website root, with an .htaccess to deny direct download of files.
// Then:
$filename = './download' . ($basename = basename($filename));
if (!file_exists($filename))
{
header('HTTP/1.0 404 Not Found');
die();
}
// A check of filemtime and IMS/304 management would be good here
// Google 'If-Modified-Since', 'If-None-Match', 'ETag' with 'PHP'
// Be sure to disable buffer management if needed
while (ob_get_level()) {
ob_end_clean();
}
Header('Content-Type: application/download');
Header("Content-Disposition: attachment; filename=\"{$basename}\"");
header('Content-Transfer-Encoding: binary'); // Not really needed
Header('Content-Length: ' . filesize($filename));
Header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
readfile($filename);
That said, what does "invalid file" mean? Bad length? Zero length? Bad file name? Wrong MIME type? Wrong file contents? The meaning may be clear to you with everything under your eyes, but from our end it's far from obvious.
UPDATE: apparently the file is not found, which means that the filename= parameter to the PHP script is wrong (refers a file that's not there). Modified the code above to allow a directory to contain all files, and downloading from there.
Your $filename variable contains whole path as below
header("Content-Disposition: attachment; filename=$filename");
Do like this
$newfilename = explode("/",$filename);
$newfilename = $newfilename[count($newfilename)-1];
$fsize = filesize($filename);
Then pass new variable into header
header("Content-Disposition: attachment; filename=".$newfilename);
header("Content-length: $fsize");
//newline added as below
ob_clean();
flush();
readfile($filename);

Force Download Files Broken Headers wrong?

if($_POST['mode']=="save") {
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/mcboeking/";
$path = $root.$path;
$file_path = $_POST['path'];
$file = $path.$file_path;
if(!file_exists($file)) {
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
readfile($file);}}
As soon as I download the file and open it I get an error message. When i try to open a .doc file I get the message: file structure is invalid.
And when i try to open a .jpg file: This file can not be opened. It may be corrupt or a file format that Preview does not recognize.
But when I download PDF files, they open without any problem.
Can someone help me?
P.s. i tried different headers including :
header('Content-Type: application/octet-stream');
$fsize = filesize($yourFilePath);
$allowed_ext = array (
// archives
'zip' => 'application/zip',
// documents
'pdf' => 'application/pdf',
'doc' => 'application/msword',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
);
$mtype = mime_content_type($file_path);
if ($mtype == '') {
$mtype = "application/force-download";
}
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: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);
//then ur rest code
Your headers have no bearing on the actual content, so the issue is that there is something wrong with the actual content.
Also, you really shouldn't try to force a download by changing the Content-Type header. Leave it what it is supposed to be. Let the client decide what to do with it.
Make sure you don't output anything but the readfile() data: ensure that PHP code begins with <? at the very first symbol of the PHP file, and that there are no symbols after the closing ?> at the end of file, like a space or a newline (or remove the ?> altogether).
Open PHP file in NOTEPAD. Press "Save as" and choose "ASCI" file format. This helped in my case, because file was in UTF8 format and this was the cause.

Files not having any content in after a header() download

I'm trying to create a download so that a user clicks on "down" it downloads a certain file from their account to their computer, I'm currently using this:
header('Content-Disposition: attachment; filename=' . basename("users/$username/$file_folder/$file_name"));
header("Content-Type:" .$file_type);
header("Content-Description: File Transfer");
header("Cache-control: private");
header("Connection: close");
header("Content-Length: ".$file_size);
The problem is, the file is downloading, but it's just empty, there is no content in the file
The code before this is just an if() and a while loop with database records.
Thanks in advance.
You are missing something like below: (unless the file is very large, in which case you would chunk it out)
$filename = 'path/to/file/file_name.txt';
echo file_get_contents($filename);
Alternatively you could populate a variable with the data you want put out into the file and simple echo it out like so:
$data = "begin\n";
$data .= "first line\n";
$data .= "another line\n";
$data .= "last line";
echo $data;
The content would be put out there AFTER your headers. Hope this helps.
The file is empty, because you never output the file. These header calls are just the header, you still need a body for a file to be correctly downloaded. You can use file_get_contents to echo the file contents.
header('Content-Disposition: attachment; filename=' . basename("users/$username/$file_folder/$file_name"));
header("Content-Type:" .$file_type);
header("Content-Description: File Transfer");
header("Cache-control: private");
header("Connection: close");
header("Content-Length: ".$file_size);
// echo the file, this will make the download work
echo file_get_contents("users/$username/$file_folder/$file_name");
after you send the headers you need to actually push out the file content...
see this
http://php.net/manual/en/function.file-put-contents.php

Serve file to user over http via php

If I goto http://site.com/uploads/file.pdf I can retrieve a file.
However, if I have a script such as:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
//require global definitions
require_once("includes/globals.php");
//validate the user before continuing
isValidUser();
$subTitle = "Attachment";
$attachmentPath = "/var/www/html/DEVELOPMENT/serviceNow/selfService/uploads/";
if(isset($_GET['id']) and !empty($_GET['id'])){
//first lookup attachment meta information
$a = new Attachment();
$attachment = $a->get($_GET['id']);
//filename will be original file name with user name.n prepended
$fileName = $attachmentPath.$_SESSION['nameN'].'-'.$attachment->file_name;
//instantiate new attachmentDownload and query for attachment chunks
$a = new AttachmentDownload();
$chunks= $a->getRecords(array('sys_attachment'=>$_GET['id'], '__order_by'=>'position'));
$fh = fopen($fileName.'.gz','w');
// read and base64 encode file contents
foreach($chunks as $chunk){
fwrite($fh, base64_decode($chunk->data));
}
fclose($fh);
//open up filename for writing
$fh = fopen($fileName,'w');
//open up filename.gz for extraction
$zd = gzopen($fileName.'.gz', "r");
//iterate over file and write contents
while (!feof($zd)) {
fwrite($fh, gzread($zd, 60*57));
}
fclose($fh);
gzclose($zd);
unlink($fileName.'.gz');
$info = pathinfo($fileName);
header('Content-Description: File Transfer');
header('Content-Type: '.Mimetypes::get($info['extension']));
header('Content-Disposition: attachment; filename=' . basename($fileName));
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($fileName));
ob_clean();
flush();
readfile($fileName);
exit();
}else{
header("location: ".$links['status']."?".urlencode("item=incident&action=view&status=-1&place=".$links['home']));
}
?>
This results in sending me the file, but when I open it I receive an error saying:
"File type plain text document (text/plain) is not supported"
First off, I'd start by checking the HTTP headers. You can do this in Firefox easily using the "Live HTTP headers" extension; not sure about equivalents in other browsers offhand. This will let you verify if the header is actually getting set to "application/pdf" and whether your other headers are getting set as well.
If none of the headers are getting set, you might be inadvertently sending output before the calls to header(). Is there any whitespace before the <?php tag?
Are you sure application/pdf is the header your browser is actually seeing?
You can check that out with various HTTP dev tools, for instance HTTP Client for the Mac or Firebug for Firefox.
I use this one and it works.
if(file_exists($file_serverfullpath))
{
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
//sending download file
header("Content-Type: application/octet-stream"); //application/octet-stream is more generic it works because in now days browsers are able to detect file anyway
header("Content-Disposition: attachment; filename=\"" . basename($file_serverfullpath) . "\""); //ok
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file_serverfullpath)); //ok
readfile($file_serverfullpath);
}
Try prepending "error_reporting(0);". I found this in the comments at http://php.net/readfile (where you took this example from).
Another thing that could be a problem is your file size. There have been issues reported in the past about PHP5 (we're talking 2005 here, so i hope this is fixed by now) having trouble reading files >2MB. If your file size exceeds this you may want to verify that it reads the whole file.

Categories