How to download pdf files using php - php

I want to download pdf files or any other file but my main motive is to download pdf files. Is it possible instead of download we can see the pdf files on browser when user submit a query.
There is my upload code this works fine`
<!DOCTYPE html>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</body>
</html>
<?php
$uploadDir = 'C:\wamp\www\images\passport images';
if(isset($_POST['upload']))
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dat";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO upload2 (name, size, type, path ) VALUES ('$fileName', '$fileSize', '$fileType', '$filePath')";
mysqli_query($conn,$query) or die('Error, query failed : ' . mysql_error());
echo "<br>Files uploaded<br>";
}
?>
**Now problem in download code**. Actually I want user submit a query in text box acc. to that text as well as it's image which is scanned So in pdf format shows to him
<?php
if(isset($_GET['id']))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_dat";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_GET['id'];
$query = "SELECT name, type, size, path FROM upload2 WHERE id = '1'";
$result = mysqli_query($conn,$query) or die('Error, query failed');
list($name, $type, $size, $filePath) = mysqli_fetch_array($result);
header("Content-Disposition: attachment; filename='".$name."'");
header("Content-length: $size");
header("Content-type: $type");
echo "<a href=" . $uploadDir .($row['userfile']) . ">
{$row['userfile']}</a>";
exit;
}
?>
`

here is my download function that you can use to download any file.
function dawnload_file($path) {
if (file_exists($path) && is_file($path)) {
// file exist
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($path));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
set_time_limit(0);
#readfile($path);//"#" is an error control operator to suppress errors
} else {
// file doesn't exist
die('Error: The file ' . basename($path) . ' does not exist!');
}
}
and here is my function for opening pdf files in the browser online.
function read_pdf_online($path){
if (file_exists($path) && is_file($path)){
// file exist
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($path));
#readfile( $path );
else {
// file doesn't exist
die('File Not Found: ' . basename($path));
}
}

Your headers tell the browser that file data will follow:
header("Content-Disposition: attachment; filename='".$name."'");
[…]
But instead of the file data you just output a link:
echo "{$row['userfile']}";
This will result in error. You have two options to fix it. Either output the link without misleading headers. When user clicks the link server will send the file to the browser. If the mime type is known to the server it will set the headers for you.
Alternatively send file data instead of link after your headers (you can read and output your file data with readfile command):
header("Content-Disposition: attachment; filename='".$name."'");
header("Content-length: $size");
header("Content-type: $type");
readfile($uploadDir . $row['userfile']);

Related

when i download the file from database then "failed to load" message display

I am trying to download the files from database. but it shows "failed to load" message.Uploading is working fine. i can upload pdf, jpg, dox file. but unable to open when i download.IF there are three href links in my file. first is for "upload" second is for "delete". every link download the file from image even other links are for other work but every file calls the downld.php file
<?php echo $name;?>
downld.php
<?php
if (isset($_GET['id']))
{
$project_id = $_GET['id'];
$myConnection= mysqli_connect("localhost","root","", "extra") or die ("could
not connect to mysql");
mysqli_set_charset($myConnection,'utf-8');
global $wpdb;
$sql = "SELECT name, type, size, content " .
"FROM wp_postprojectwin WHERE project_id = $project_id";
$result = mysqli_query($myConnection,$sql) or die('Error, query failed');
list($name, $type, $size, $content) = mysqli_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Description: PHP Generated Data");
header("Content-Transfer-Encoding: binary");
mysqli_close($connection);
ob_clean();
flush();
echo $content;
exit;
}
else{
echo "sorry";
}
?>

Failed to load PDF document in my PHP code

I am new to PHP and trying to implement below functionality through code give
Functionality:
I have one Download button and upon clicking i should be able to download my .pdf file stored under htdocs-->xxfilename-->abc.pdf;
Code:
I am using below code in my xyz.php web page
<?php
$title = "Learning";
$content = '
<h3> Intro</h3>
<p>
Introduction goes here
</p>
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download" name="dwnld_file"/>
</form>
';
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("PQR");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = '$row["col2"]';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $row["col2"] . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile($file);
}
}
include 'Template.php';
?>
Error:
My pdf file is getting downloaded but upon opening it it says "failed to load pdf document"
Please help where i am wrong.
***Edit****
I tried different approach and my file is downloading but still it says "failed to load pdf document"
My other approach code is below
<form action = "xyz.php" method = "post" name = "downloadform">
<input type="submit" value="Download " name="dwnld_file"/>
</form>
<?php
if (isset($_POST['dwnld_file'])) {
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$res = mysql_query("Select * from tab1");
while ($row = mysql_fetch_array($res)) {
$file = $row["col1"];
echo $file;
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' .$file. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Content-Length:' . filesize($file));
readfile('myfile/'.$file);
}
}
?>
Please tell me if i am doing anything wrong.
I implemented another solution after doing some more study and i was able to solve the problem.
Below is my code i used to implement.
Concept:
1) We can use HTML+JSP+PHP to get this functionality.
2) At HTML + JSP side we need to call eventListener to capture the event of clicking the button.
3) This event will redirect to the php page which will download the pdf file to your local computer.
Code Snippet:(here XYZ is the name of page where you want to show Download button)
in XYZ.php
<input type="button" id="btnshow" value="Download" name="dwnld" />
<script>
var btn = document.getElementById('btnshow');
btn.addEventListener('click', function () {
document.location.href = '<?php echo 'download.php'; ?>'
})
</script>
in download.php
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("database_name");
$res = mysql_query("Select * from table_name");
while ($row = mysql_fetch_array($res)) {
$file = 'Pdf_File/' . $row["Path"];
$filename = $row["Path"];
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($file);
}
?>
Hope it help some one out there newbie like me.
Happy Coding!

Uploaded file is unable to read after downloading in PHP

I wrote php script to upload file from admin panel and to download for user.
Uploading was done successfully but after downloading the file, it is unable to read. if it is a image file or pdf file. The uploaded files are copied to xamp/htdocs/myproject/admin/documents. and the path is stored to mysql database. When i tried to download it the file size is different for uploaded file and downloaded file and it is unable to read.
The uploading script
if (isset($_POST['submit'])){
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name) {
$location = "documents/$name";
move_uploaded_file($tmp_name, $location);
$query = mysqli_query($con,"INSERT INTO posts (name,path) VALUES ('$location')");
}
Thanks everybody for helping me. i made changes for my script yesterday and it is working but the problem is that when i tried to add it to my project it is not working.
my uploads script(it is writen in myproject/admin/application.php)
if (isset($_POST['submit'])){
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
if ($name) {
$location = "documents/$name";
move_uploaded_file($tmp_name, $location);
$query = mysqli_query($con,"INSERT INTO posts (name,path) VALUES ('$location')");
}
download.php (Written in myproject/download.php)
<?php
include('includes/connect.php');
if (isset($_GET['dow'])) {
$path = $_GET['dow'];
$res = mysqli_query("SELECT * FROM posts WHERE path = '$path'");
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . basename($path) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
flush();
readfile($path); //showing the path to the server where the file is to be download
exit;
}
?>
The linking script to download.php b (written in myproject/viewprofile.php)
<?php
include('includes/connect.php');
$sql = "SELECT * FROM posts";
$res = mysqli_query($con, $sql);
$path = $row['post_path'];
echo "<a href='download.php?dow=$path' class='btn btn-dark btn-theme-colored btn-flat mr-5' style='width:100%; margin-top:5px;'> DOWNLOAD RESUME </a> <br>";
?>

Download empty BLOB file from MySQL DB PHP

I'm trying to download a XML file from my DB. The file is stores in a BLOB field, but when I open the page it dowloads a blank xml file.This is my function:
<?php
$conexao = mysql_connect("db","user","pss") or die('Not connected : ' . mysql_error());
mysql_select_db("db", $conexao) or die (mysql_error());
$result = mysql_query("select * from xmlNFe where xml_id = 1", $conexao);
$row = mysql_fetch_array($result);
$xml = $row['xml_xml'];
$nome = mysql_result($result, 0, 'xml_chNFe');
header('Content-type: application/octet-stream');
header('Content-Description: File Transfer');
header("Pragma: public");
header("Content-Disposition: attachment;filename=".$nome.".xml");
header('Content-Transfer-Encoding: binary');
header("Content-length: ".filesize($xml));
header('Accept-Ranges: bytes');
ob_clean();
flush();
echo $xml;
mysql_close($conexao);
exit;
?>
Does anyone have any idea?
header("Content-length: ".filesize($xml));
^^^^
$xml is your actual xml data, it's NOT a filename, so filesize() will FAIL and return boolean FALSE. You cannot get the size of a file which does not exist.
Try
header("Content-length: ".strlen($xml));
^^^^^^
instead.

PHP headers putting everything that was output to screen into downloaded file

I have the following PHP code using headers to download a file from the server:
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
This code works fine, however I have it in a file with the HTML form and it is ran using an if isset all of the HTML code is placed in the file, as well as anything I echo out in PHP; and the data I actually want in the file is there at the end.
I can't figure out what in the headers is causing it to write everything that is on screen to the file when downloaded. The file on he server isn't changed and is how it should be.
Thanks for any help.
Heres all the code...
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"><br>
Order Number: <input type="number" name="orderNo" size="10"/>
<input type="submit" name="Download" value="Download" />
</form>
</body>
</html>
<?php
if(isset($_POST['Download'])){download();}
function download()
{
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('amazondb', $conn);
$result = mysql_query("SELECT ID, PurchaseDate, BuyerName, ShipCity, ShipState, ShipPostalCode, ShipCountry,
ShipAddress1, ShipAddress2, ShipAddress3 FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($row['ID']==($orderNo))
{
echo "Hello";
fwrite($file, $row['BuyerName'].PHP_EOL .$row['ShipAddress1'].PHP_EOL .$row['ShipAddress2'].PHP_EOL .$row['ShipAddress3'].PHP_EOL .$row['ShipCity'].PHP_EOL .$row['ShipState'].PHP_EOL .$row['ShipPostalCode'].PHP_EOL .$row['ShipCountry'].PHP_EOL);
}
}
fclose($file);
$file = 'Order.txt';
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
else{echo "Please enter a valid Order Number"; echo $orderNo;}
}
move this code at very begin of file, so you will have:
<?php
if (your condition to output file) {
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
die();
}
the rest of your file....
another solution, at the very top of file add:
<?php
ob_start() or die('Cannot start output buffering');
... your page
and just before the first header add:
$file = 'Order.txt';
ob_end_clean();
header("Cache-Control: public");
...
readfile($file);
die();

Categories