Set page title when viewing PDF through php script - php

I am using this code to view an PDF file in php instead of just opening it in an browser.
if(isset($_SESSION['access_token']))
{
require_once('includes/db_connect.php');
$id = mysqli_real_escape_string($mysqli, $_GET['id']);
$attest = mysqli_real_escape_string($mysqli, $_GET['attest']);
$heat = mysqli_real_escape_string($mysqli, $_GET['heat']);
$mat = mysqli_real_escape_string($mysqli, $_GET['mat']);
$dikte = mysqli_real_escape_string($mysqli, $_GET['dikte']);
$file = '../thure/uploads/attesten/'.$id.'.pdf';
$filename = 'Certificaat plaat '.$id.' met '.$attest.' heat '.$heat.' '.$mat.' '.$dikte.'mm.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}
The title of the page as Shown in Explorer, Chrome etc. is the name of the php file. How can I set an custom name (same as PDF) here?
When I use the code below the pdf is shown as plain text.
<!DOCTYPE html>
<head>
<title>Torza</title>
</head>

Related

how to not automatically download files in php

Hello I'm doing my project and i want to ask just a simple question. Every time I go to that page it downloads automatically without getting inside on that page. When I click the button it automatically download the files. But I want to go that page and click a link before downloading it. Anyone help?
if(isset($_GET['profile']))
{
$id=$_GET['profile'];
$query = "SELECT * FROM profile_table WHERE id=?";
$stmt=$con->prepare($query);
$stmt->bind_param("i",$id);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$vid = $row['id'];
$vfname = $row['fname'];
$vlname = $row['lname'];
$vmname = $row['mname'];
$vsex = $row['sex'];
$vage = $row['age'];
$vbday = $row['bday'];
$vbloodtype = $row['bloodtype'];
$vheight = $row['height'];
$vweight = $row['weight'];
$vreligion = $row['religion'];
$vcolorhair = $row['colorhair'];
$vdistmark = $row['distmark'];
$vmobile = $row['mobile'];
$vtin = $row['tin'];
$vphealth = $row['phealth'];
$vlegaldep = $row['legaldep'];
$vaddress = $row['address'];
$vtsize = $row['tsize'];
$vheadgear = $row['headgear'];
$vshoes = $row['shoes'];
$vuniform = $row['uniform'];
$vphoto = $row['photo'];
$vsoi = $row['soi'];
if (file_exists($vsoi)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($vsoi));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('documents/' . $row['name']));
readfile('documents/' . $row['name']);
}
}
I think the problem their is the file_exist in vsoi. And I dont know what to do or to change in my code. I appreciate all the answers. TIA!
I think first you need to understand what your code is trying to do, e-g
if (file_exists($vsoi)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($vsoi));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('documents/' . $row['name']));
readfile('documents/' . $row['name']);
}
Above code is used to when we want to force a browser to download a file.
But in your case you only want to download the file when the page is loaded and user clicks on a download link and then the download starts.
It can be achieved by just displaying a download link which will then execute the same code you wrote in the if statement.
So change your if statement as following and then write the same code which was in the if statement previously to that download link page.
if (file_exists($vsoi)) {
echo 'Download File
}
You can simply display a direct download link to the file as following.
<php
$download_link = 'https://yourdomain.com/files/sample.pdf';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Sample file</h1>
Download
</body>
</html>

Displaying PDF to Browser with PHP not working

Using php's ability to call upon the browser to display a given PDF it doesn't work on my web host. But it works on my local xamp server with apache.
PHP:
$title = $_GET['title'];
$loc = $_GET['loc'];
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$title);
#readfile($loc);
Expected Output: Supposed to be the PDF document being rendered like it does on my local web server.
Actual but unwanted output:
%PDF-1.6 %���� 1638 0 obj <> endobj xref 1638 44 0000000016 00000 n ...
Can be seen here:
http://neilau.me/view.php?title=business-studies-hsc-notes-2006.pdf&loc=pdf/criteria/business-studies/2006/business-studies-hsc-notes-2006.pdf
Is this fixed through changing something on my cpanel? As my code isn't faulty... It works on my local web server.
Use this code
<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
?>
You need to make sure you are not sending any text before writing headers.
Example of what not to do:
<!DOCTYPE html>
<html>
...
<?php
header("Content-type: application/pdf");
Example of how to fix that:
<?php
header("Content-type: application/pdf");
?>
<!DOCTYPE html>
<html>
...
In addition your script is very insecure. Here's what you should do, your entire PHP script should be:
<?php
$loc = filter_input(INPUT_GET,"loc");
$title = filter_input(INPUT_GET,'title')?:basename($loc);
if (!is_readable($loc)) {
http_response_code(404);
echo "Cannot find that file";
die();
}
if (strtolower(pathInfo($loc,PATHINFO_EXTENSION)) != "pdf") {
http_response_code(403);
echo "You are not allowed access to that file";
die();
}
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$title);
header("Content-Length: ".filesize($loc));
readfile($loc);
If you want to show things like a page title or a frame around it, you should use an iframe in another "wrapper" page:
<?php
$loc = filter_input(INPUT_GET,"loc");
$title = filter_input(INPUT_GET,'title')?:basename($loc);
?>
<html><head><title>My title</title></head>
<body>
<iframe src="/view.php?<?php echo ($loc?"loc=$loc":"").($title?"title=$title":"") ?>">
</iframe>
</body>
<html>

PHP echo before setting content type header?

I have the following PHP code:
function download_file($file, $description=null, $filename=false){
$filename = $filename || basename($file);
ob_start();
if(is_string($description)){
$description = preg_replace("/\$1/", $filename, $description);
echo $description;
}
sleep(2);
header('Content-Type: '.$this->file_mimetype($file));
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");
readfile($file);
header("Content-Type: text/html");
ob_end_flush();
}
download_file("https://raw.githubusercontent.com/Gethis/ED/master/easydevop.class.php", "Downloading easydevop.class.php");
The problem is that it is not echoing "Downloading easydevop.class.php" before the download. I also tried echoing it after all the headers, but that didn't work either. Please, any help?
As you can see I did use ob_start() and ob_end_flush()
You can't use "echo" (showing HTML-content) and send file to user at the same time.
You can show HTML-page first, and then redirect user to the file, using
HTML-redirect
<META HTTP-EQUIV="REFRESH" CONTENT="0;URL=http://url.to/file/or_script/that_send_file/">
or javascript redirect How do I redirect with Javascript?
As I already mentioned you cannot display echo when downloading file. When you download file you can just download file, nothing more.
However using JavaScript you can display message before starting downloading. Here is the test script:
<?php
if (isset($_GET['id'])) {
$file = 'testfile.txt';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script type="text/javascript">
function showDownload(message) {
document.getElementById("hidden").innerHTML = message;
document.getElementById("link1").style.display = 'none'; // you can even hide download link if you want
}
</script>
<div id="hidden"></div>
Download
</body>
</html>

downloading pdf file using php and html link

i have written some code to select a row from a database and generate a link. the link is working ok but when i try to download the pdf i get this:
����)�^�z8��AQ�[��rr�=��73KJ��KR]�PD�H�����>3;,;~˾����ɫS����/ؤ���,������=??<8��3��L�����e�\I�aN�i.����A�.�����������|x�F�oN���1>MʙJ�#�Mz�'�N��?K��sx`D�5gژ�r&�N3��M�f����߱9<]R��,))�dj���D#k&O-�7V����M��d�I��HMN=��9��/�ubS���`189\S�����f�p_��T�T�&ӭ���E>�O�)eAœ
displaying on the page.
my code is:
<?php
$sql="SELECT * from table1 where invoice_number = '".$_GET["inv"]."' and sequence = '".$_GET["seq"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
if(mysql_num_rows($rs) > 0)
{
$result=mysql_fetch_array($rs);
$file = 'http://www.domain.co.uk/invoices/'.$result["pdf"].'';
$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
#readfile($file);
}
?>
any ideas how i can make it download the file rather than try and display it in the browser. please note, its a shared hosting server so i cannot make many changes on the actual server itself
Change the following:
header('Content-Disposition: inline; filename="' . $filename . '"');
to
header('Content-Disposition: attachment; filename="' . $filename . '"');

Php function to save a image

I have some images used for the avatars of the users on my website, for example http://drksde.tk/images/avatar-Luxie.jpeg
I want to add a link that allow the users to download the avatar image, when someone click in the link a Save As dialog should appear.
Now the problem is that the picture is not downloaded properly, but the dialog appears, here is the link to download the avatar, and the code:
<?php
$username = $_GET['username'];
$size = $_GET['size'];
$ext = $_GET['ext'];
$border = $_GET['border'];
$basename = basename($_SERVER['REQUEST_URI']);
if(!isset($size)) { $size = 'small'; }
if(!isset($ext)) { $ext = 'jpeg'; }
if(!isset($border)) { $border = 'true'; }
$file = 'avatar-'.$size.'-'.$username.'.'.$ext;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$basename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
#header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
?>
You can check out Example #1 in the php.net manual here:
http://php.net/manual/en/function.readfile.php
It shows how to force an image download.
You could place it into a script image.php and use it like this
download avatar image
You could use it with the $_GET['user'] parameter to serve the right user image file.
Just remember to validate the GET input.

Categories