PHP: open a file download dialog [duplicate] - php

This question already has answers here:
Force file download with php using header()
(7 answers)
Closed 9 years ago.
I have an MPEG file (.mpg) hosted in Amazon S3, that I want to link to a page I have, so the user will be able to download it from the page.
I have in my page a link:
bla bla"
The link to the file works when I right-click it and choose "Save Target As" , but I would like it to work also when I left click it, and that it will open a file download dialog. right now, a left click will direct to a page that has the video directly played in it (in FireFox) or just won't load (in Internet Explorer).
I am working in PHP, why does this happen?

You probably want to wrap the file within a "download" PHP script that sends the appropriate Content-Disposition header telling the browser to treat it as a download instead of a content item.
For instance:
header("Content-Disposition: attachment; filename=yourfilenamehere.ext>");
http://support.microsoft.com/kb/260519

This will work with UTF-8 filenames (say you have one in a variable called $orfilename):
function detectUserAgent() {
if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
return "Other";
$uas = $_SERVER['HTTP_USER_AGENT'];
if (preg_match("#Opera/#", $uas))
return "Opera";
if (preg_match("#Firefox/#", $uas))
return "Firefox";
if (preg_match("#Chrome/#", $uas))
return "Chrome";
if (preg_match("#MSIE ([0-9.]+);#", $uas, $matches)) {
if (((float)$matches[1]) >= 7.0)
return "IE";
}
return "Other";
}
/*
* We have 3 options:
* - For FF and Opera, which support RFC 2231, use that format.
* - For IE and Chrome, use attwithfnrawpctenclong
* (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
* - For the others, convert to ISO-8859-1, if possible
*/
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';
switch (detectUserAgent()) {
case "Opera":
case "Firefox":
$orfilename = rawurlencode($orfilename);
$format = $formatRFC2231;
break;
case "IE":
case "Chrome":
$orfilename = rawurlencode($orfilename);
$format = $formatDef;
break;
default:
if (function_exists('iconv'))
$orfilename =
#iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
$format = $formatDef;
}
header(sprintf($format, $orfilename));

On download page do the following
$filename = $_GET['movie']; //Get the filename
if(is_file($filename)) {
//If you want to read and output the contents do it here
header('Content-disposition: attachment; filename='.$filename);
}
exit();
This will tell the browser to treat this as an attachment, thus forcing a download box.

Related

how to convert page to pdf in php

I have an html page like JsFiddle and I want convert this in pdf, i can't create the line to line pdf because the page is dinamically create, I use php for calling a fiel that connect to mysql and fill a template file like.
$_POST['IdQuestionario']=5;
$_POST['IdUtente']=10001;
$_POST['Visualizza']=true;
$_POST['IdImpianto']=1;
$_POST['Stampa']=true;
$_POST['TipoImpianto']='grande';
ob_start();
ob_clean();
require_once 'intro.php';
$tbl=ob_get_clean();
$html.=$tbl;
I'm trying with tcpf, mpdf , jsPDF but i cant obtain a discrete output because I use colgroup for table. anyone say me a method for render the page,if is possible whitout install software on server.
There a few that i know of - some have problems with tables, I would avoid DOMPDF - known issues with tables.
There's one that's recommended from cvision; i don't have a code sample, but you can download it free and even sample it online.
There's also a php-pdf product available from muhimbi (a little lesser-known!, but i think it's free)
<?php
// Include the generated proxy classes
require_once "documentConverterServices.php";
// Check the uploaded file
if ($_FILES["file"]["error"] > 0)
{
echo "Error uploading file: " . $_FILES["file"]["error"];
}
else
{
// Get the uploaded file content
$sourceFile = file_get_contents($_FILES["file"]["tmp_name"]);
// Create OpenOptions
$openOptions = new OpenOptions();
// set file name and extension
$openOptions->FileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$openOptions->OriginalFileName = $_FILES["file"]["name"];
// Create conversionSettings
$conversionSettings = new ConversionSettings();
// Set the output format
if(isset($_POST["outputFormat"]))
{
$conversionSettings->Format = $_POST["outputFormat"];
} else {
$conversionSettings->Format = "PDF";
}
// Set fidelity
$conversionSettings->Fidelity = "Full";
// These values must be set to empty strings or actual passwords when converting to non PDF formats
$conversionSettings->OpenPassword="";
$conversionSettings->OwnerPassword="";
// Set some of the other conversion settings. Completely optional and just an example
$conversionSettings->StartPage = 0;
$conversionSettings->EndPage = 0;
$conversionSettings->Range = "VisibleDocuments";
$conversionSettings->Quality = "OptimizeForPrint";
$conversionSettings->PDFProfile = "PDF_1_5";
$conversionSettings->GenerateBookmarks = "Automatic";
$conversionSettings->PageOrientation="Default";
// Create the Convert parameter that is send to the server
$convert = new Convert($sourceFile, $openOptions, $conversionSettings);
// Create the service client and point it to the correct Conversion Service
$url = "http://localhost:41734/Muhimbi.DocumentConverter.WebService/?wsdl";
$serviceClient = new DocumentConverterService(array(), $url);
// If you are expecting long running operations then consider longer timeouts
ini_set('default_socket_timeout', 60);
try
{
// Execute the web service call
$result = $serviceClient->Convert($convert)->ConvertResult;
// Send the resulting file to the client.
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"convert." . $conversionSettings->Format . "\"");
echo $result;
}
catch (Exception $e)
{
print "Error converting document: ".$e->getMessage();
}
}
?>
Also, you could investigate 'Snappy' (has dependencies)
You can try WKHTMLTOPDF.
Here is a Stackoverflow Thread on how to use it with PHP.
How do I get WKHTMLTOPDF to execute via PHP?
And here is a wrapper for PHP
https://github.com/mikehaertl/phpwkhtmltopdf
MPDF one of best library to convert pdf, try it
MPDF link : http://www.mpdf1.com/mpdf/index.php
Example link : http://mpdf1.com/common/mpdf/examples/

Mozilla pdf.js, How to I specify the filename for download?

I pass the location of the php file that contains the following code as parameter to the viewer.html file and it is displayed correctly but when clicking the download button in the pdf viewer the document name is always document.pdf. This poses a problem because of how many mobile users will be downloading files only to discover that all of their files have the the name document.pdf and that they (for most mobile browsers) can't change the filename before downloading.
Do I have to pass some arbitrary parameter to the file or redirect to self with the filename appended?
<?php
$content = "a binary representation of my pdf";
header("Content-type: application/pdf");
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="someFile.pdf"');
echo $content;
?>
I've run into this same issue. From the pdf.js's viewer.js source:
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') != -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
So the majic needs to come from the URL via the reURI regexp.
What you need to do is this:
http://domain.com/path/to/Named.pdf
http://domain.com/path/to/your/api?fileId=123&saveName=Named.pdf
Each of these will result in a save as filename of Named.pdf thanks to the regexp code above.
Based on comments
You can add this to wherever you're using the viewer.js file.
setTimeout(() => {
// Wait for PDFViewerApplication object to exist
PDFViewerApplication.setTitleUsingUrl('custom-file.pdf');
}, 10);
Then when you download the PDF it will have that filename

File only downloading when opened in new window/tab

I have a function that creates different file types depending on a variable, I have it generating an XML, but when I click the link to the page to do so (XML), nothing happens. If I click to open it in a new tab or manually enter the url in the title bar then the file will download as I want it to.
function asset($asset_id, $display = ''){
$this->load->model('model_asset');
$asset = $this->model_asset->get_by_id($asset_id, true);
switch($display) {
case 'xml':
$this->load->helper('array_to_xml_helper');
$asset_arr = get_object_vars($asset);
$filename = $asset->title .'-'. $asset->subtitle . '.xml';
$xml = Array2XML::createXML('asset', $asset_arr);
header ("Content-Type:text/xml");
header('Content-Disposition: attachment; filename="'. $filename .'"');
echo $xml->saveXML();
break;
}
}
How can I make this work with dynamically generated files (I'm using a arraytoxml utility function I found here)
You can try to set file in attachement
Add this to your headers :
Content-disposition: attachment
filename=huge_document.pdf

PHP force download and refresh SOLUTION not working

End goal:
Click link on page 1, end up with file downloaded and refresh page 1. Using PHP to serve downloads that are not in public html.
Approach:
Page 1.
Link transfers to page 2 with get variable reference of which file I am working with.
Page 2.
Updates relevant SQL databases with information that needs to be updated before refresh of page 1. Set "firstpass" session variable. Set session variable "getvariablereference" from get variable. Redirect to page 1.
Page 1.
If first pass session variable set. Set Second pass session variable. Unset first pass variable. Refresh Page. On reload the page will rebuild using updated SQL database info (changed on page 2.).
Refreshed Page 1.
If second pass session variable set. Run download serving header sequence.
This is page 1. I am not showing the part of page 1 that has the initial link. Since it doesn't matter.
// REFERSH IF FIRSTPASS IS LIVE
if ($_SESSION["PASS1"] == "YES"){
$_SESSION["PASS1"] = "no";
$_SESSION["PASS2"] = "YES";
echo "<script>document.location.reload();</script>";
}
if ($_SESSION["PASS2"] == "YES"){
// Grab reference data from session:
$id = $_SESSION['passreference'];
// Serve the file download
//First find the file location
$query = "SELECT * from rightplace
WHERE id = '$id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$filename = $row['file'];
$uploader = $row['uploader'];
// Setting up download variables
$string1 = "/home/domain/aboveroot/";
$string2 = $uploader;
$string3 = '/';
$string4 = $filename;
$file= $string1.$string2.$string3.$string4;
$ext = strtolower (end(explode('.', $filename)));
//Finding MIME type
if($ext == "pdf" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/pdf');
readfile($file);
}
if($ext == "doc" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/msword');
readfile($file);
}
if($ext == "txt" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: text/plain');
readfile($file);
}
if($ext == "rtf" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/rtf');
readfile($file);
}
if($ext == "docx" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
readfile($file);
}
if($ext == "pptx" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
readfile($file);
}
if($ext == "ppt" && file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/vnd.ms-powerpoint');
readfile($file);
}
}
The script on page 2 is working correctly. It updates the sql database and redirects to the main page properly. I have also checked that it sets the "$_SESSION['passreference'];" correctly and nothing on page 1 would unset it.
So, thats the whole long explanation of the situation. I am stumped. What happens is, as I said page 2 works fine. Then it kicks to page 1, refreshes and then doesnt push any download. I know that the download script works and that the files are there to be downloaded (checked without the whole refresh sequence).
I essentially have two questions:
Can anyone spot whats going wrong?
Can anyone conceptualize a better approach?
It is hard to debug something like this remotely even given the code, the segment you posted works as you say. Have you checked your error logs? The most likely culprit is a problem with sending header() after other output has been done.
When dealing with file downloads, I think it is easier wherever possibly to initiate the download on a new page/window so there can be no risk of breaking headers. Maybe a slightly altered sequence using a third page that initiates the actual download:
Page 1 links to the second page to do magic, which redirects back to page 1
Page 1 then spawns page 3 in a new window, which initiates the download.
There's a good example code for loading a new window for a download in this answer.
Looking at your code, the download problem may be that the $ext variable contains an unexpected value or that the $file variable contains the name of a file that really doesn't exist.
In either this cases, none of your "if" conditions would be true, so the download would'nt start.
My suggestion is to add the following statements just before the "//Finding MIME type" comment line:
$log = "file='".$file."'\n";
$log .= "ext='".$ext."'\n";
#file_put_contents("/tmp/page1.log", $log, FILE_APPEND);
This way, looking at the "/tmp/page1.log" file you should be able to check if the $file and $ext variabiles effectively contain the expected values.
I've used "/tmp/page1.log" as the log file name since I suppose that you're working on linux; if not, please adjust the first argument of the "file_put_contents" function with a valid path and file name for your enviroment.
Also, I would replace the sequence of "if" tests with the following code:
$content_types = array(
"pdf" => "application/pdf",
"doc" => "application/msword",
"txt" => "text/plain",
"rtf" => "application/rtf",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation"
);
if (isset($content_types[$ext])) {
if (file_exists($file)) {
header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: '.$content_types[$ext]);
readfile($file);
die("");
} else {
die("** '".$file."' does not exist **");
}
} else {
die("** Unhandled '".$ext."' extension **");
}
Obviously, you should implement the error handling in a much more robust way, not simply using the "die()" function as I did, but this is only an example.
Finally, be aware that there are also better ways of getting the content-type corresponding to the file extension; for example one solution is to use the PHP Fileinfo functions.
Have a look at this answer for further information about this topic.
Keep also in mind that in safe mode the file_exists function always returns FALSE, and that the results of the file_exists function are cached; see the clearstatcache() function on the PHP manual for further details.
I just reworked your PHP code a bit. Especially you'll get more information about what's going wrong. Just try this code and read the following comments, which explain what happend, if you get one of the new error messages. Also read the NOTE part below, which explains why you probably can't access a file from PHP, even it's existing and is in the right directory.
Using window.location.reload(); instead of document.location...
I added an error()-function. You can add more HTML to it, so it's producing a page in the layout you want. And you could log the error to a local file, too. There is a private info parameter used to pass sensible information as database errors (can contain SQL) to the function. For productive use you shouldn't display that to the user. Instead you can log it into a file or only display it for privileged users (e.g. Administrators).
Checks weather $id is set. Returns error() message if not; Could happen if session was not updated correctly.
I added "$id = addslashes($id);" for security reasons. If your id could be set to values like $id = "' OR 1" (SQL-Injection) for example, you could get into trouble. If you are sure this can not happen, you can remove it.
It checks the $result variable after the DB query. If e.g. your database connection wasn't established or the script cannot connect this will produce an error()-output that informs you. The same happens if you have an error in your SQL syntax, e.g. wrong table name.
It's also checked weather a valid $row is fetched from the database. If there isn't a row returned your $id is problably wrong (there isn't such an entry in your database).
I rewrote your string operations to $filepath = $rootpath . "/" . $uploader . "/" . $filename; where $rootpath is set before without "/" at the end; This is easier to read...
Extensions and MIME-Types are now put into an array, instead of using a lot of "if-then"-blocks, that's easier to maintain. Also the code inside that blocks were similar... so we only need to write it once.
A default MIME type (Content-Type:"application/octet-stream) is sent, if the file extension is not known.
We check for file_exists() and output an error message, with $filename given to allow checking weather the path is correct...
So here is the source code:
<?php
function error($message, $info = "") {
echo "ERROR: $message<br>";
echo "PRIVATE-INFO: $info"; // probably you only want to log that into a file?
exit;
}
// REFERSH IF FIRSTPASS IS LIVE
if ($_SESSION["PASS1"] == "YES") {
$_SESSION["PASS1"] = "no";
$_SESSION["PASS2"] = "YES";
echo "<script>window.location.reload();</script>";
exit;
}
if ($_SESSION["PASS2"] == "YES") {
// Grab reference data from session:
$id = $_SESSION['passreference'];
if (!$id) error("Internal Error ('id' not set)");
// Select file location from DB
$id = addslashes($id);
$query = "SELECT * from rightplace WHERE id = '$id'";
$result = mysql_query($query);
if (!$result) error("DB-query execution error", mysql_error());
$row = mysql_fetch_array($result);
mysql_free_result($result);
if (!$row) error("File with ID '$id' was not found in DB.");
$filename = $row['file'];
$uploader = $row['uploader'];
// Setting up download variables
$rootpath = "/home/domain/aboveroot";
$filepath = $rootpath . "/" . $uploader . "/" . $filename;
$ext = strtolower(end(explode('.', $filename)));
// Serve the file download
// List of known extensions and their MIME-types...
$typelist = array(
"pdf" => "application/pdf",
"doc" => "application/msword",
"txt" => "text/plain",
"rtf" => "application/rtf",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"ppt" => "application/vnd.ms-powerpoint"
);
// set default content-type
$type = "application/octet-stream";
// for known extensions, assign specific content-type
if (!isset($typelist[$ext])) $type = $typelist[$ext];
if (file_exists($filepath)) {
header("Content-disposition: attachment; filename= '$filename'");
header("Content-type: $type");
readfile($filepath);
} else {
error("Error: File '$filepath' was not found!", $filepath);
}
}
?>
NOTES:
The file not found error can happen even the file exists. If this happens, this is most probably a security mechanism that prevents the PHP script to access files outside the HTML-root directory. For example php scripts could be executed in a "chrooted" environment, where the root directory "/" is mapped e.g. to "/home/username/". So if you want to access "/home/username/dir/file" you would need to write "/dir/file" in your PHP script. It can be even worse, if your root is set like "/home/username/html"; then you'll not be able to access directories below your "html" directory. To work around that, you can create a directory inside the HTML-root and put a file named ".htaccess" there. Write "DENY FROM ALL" in it, which prevents access to the directory by browser request (only scripts can access it). This works for apache servers only. But there are solutions like that for other server software too... More info on this can be found under: http://www.php.net/manual/en/ini.core.php#ini.open-basedir
Another possibility is that your file access right (for uploaded files) are not set in a way, that your script is allowed to access them. With some security settings enabled (on a linux server), your PHP script can only access files owned by the same user as the "owner" set for the script file. After upload via "ftp" this is most probably the usersname of the ftp user. If edited on the shell, this will be the current users username. => But: Uploaded files are sometimes assigned to the user the webserver is running as (e.g. "www-data", "www-run" or "apache"). So find out which it is and assign your script to this owner.
For file uploads you should use move_uploaded_file(...) which is explained here: www.php.net/manual/en/function.move-uploaded-file.php ; If you don't do this, the file access right may be wrong or you might not be able to access the file.

Why do images served from my web server not cache on the client?

I store all of my images behind the webroot (before /var/www/), which means that the web server is unable to send cache headers back for my pictures. What do I need to add to this to make the user's web cache work? Currently, this is getting hit every time by the same browser.
My <img> path on my pages look something like this:
<img src="pic.php?u=1134&i=13513&s=0">
Edit: Could it be that it is because "pic.php?u=1134&i=13513&s=0" is not a valid file name or something?
// pic.php
<?php
// open the file in a binary mode
$user = $_GET['u'];
$id = $_GET['i'];
$s = $_GET['s'];
if (!isset($user) && !isset($s) && $isset($id))
{
// display a lock!
exit(0);
}
require_once("bootstrap_minimal.php"); //setup db connection, etc
// does this image_id belong to the user?
$stmt = $db->query('SELECT image_id, user_id, file_name, private FROM images WHERE image_id = ?', $id);
$obj = $stmt->fetchObject();
if (is_object($obj))
{
// is the picture is the users?
if ($obj->user_id != $_SESSION['user_id'])
{
// is this a private picture?
if ($obj->private == 1)
{
// check permissions...
// display a lock in needed!
}
}
}
else
{
// display a error pic?!
exit(0);
}
if ($s == 0)
{
$picture = $common->getImagePathThumb($obj->file_name);
}
else
{
$picture = $common->getImagePath($obj->file_name);
}
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($picture));
$fp = fopen($picture, 'rb');
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
You need to add something like:
$expiry = 3600*24*7; // A week
header('Expires: ' . gmdate('D, d M Y H:i:s' time() + $expiry) . ' GMT');
header('Cache-control: private, max-age=' . $expiry);
Apache only caches static files by default. You need to send a cache control header via the header() function. This article has a lot of information on the topic.
Alternatively, you could use the PHP file to redirect to the actual location of the image. (This is probably the easiest way if you don't know anything about headers.)
You might try:
header("Cache-Control: max-age=3600");
That should send a cache timeout of one hour on the file.
What I would do in your situation is to stream the bytes of the image using a .php file. Don't link to images directly; instead, link to a php file that:
- outputs the cache headers
- reads the file off of disk, from behind the webroot
- sends the image bits down the wire
Simple answer: you aren't telling your users' browser to cache it

Categories