I'm storing pdf's on the filesystem and path in database table. I want now based on the ID to open corresponded PDF document in the browser. How can I open and read PDF's?
What I have so far is this
require_once("database.php");
if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
$fileFolder='uploads/';
$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();
$resArray = $result->fetchAll();
$file = $resArray['file'];
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileFolder.$file));
#read($fileFolder.$file);
}
When I click on the button and tried to open the pdf I got this message in the Chrome
Failed to load PDF document
RELOAD
You can get your file name using fetch(PDO::FETCH_ASSOC); which Return next row as an array indexed by column name
$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();
$resArray = $result->fetch(PDO::FETCH_ASSOC);
$file = $resArray['file'];// get your file name
By using fetchAll
Pass PDO::FETCH_COLUMN, 0
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$file = $resArray[0];// get your file name
try the following:
require_once("database.php");
if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
$fileFolder='uploads/';
$sql = "SELECT file FROM documents WHERE upload_id = :id";
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();
$resArray = $result->fetchAll();
$file = $resArray['file'];
$myFilePath = $fileFolder . $file;
if (file_exists($myFilePath)) {
// the file exists, so open it
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($fileFolder.$file));
#read($fileFolder.$file);
} else {
// the file doesn´t exits
// handle the error if neccessary
echo "the file doesn´t exist";
}
}
Related
I have a MySQL-DB, which contains SSL certificate private keys and the certificate. My goal is to create a PHP script, that creates a pkcs12-file and sends it to browser/download.
Thats my code:
<?php
$certid = "22";
$sqltran = mysqli_query($connection, "SELECT * FROM certificates WHERE id=$certid ")or die(mysqli_error($connection));
$row = mysqli_fetch_array($sqltran);
extract($row);
$privateKeyPass = "mypassword";
$pkey = openssl_pkey_get_private($privatekey, $privateKeyPass);
$rc = openssl_pkcs12_export($certificate, $pkcs12, $pkey, "exportpassword");
if (!($rc === true)) {
echo ('Failed to export PKCS12 Certficate Store.');
die('getpkcs12.php');
}
header('Pragma: private');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private');
header('Content-Description: File Transfer');
header('Content-Type: application/x-pkcs12');
header('Content-Disposition: attachment; filename="' . $commonname . '.p12"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($pkcs12));
print($pkcs12);
?>
It creates a file and provides a download with the correct filename; but I cannot import the p12-file in any system (invalid file).
Just tried to generate the pkcs12-file with function
openssl_pkcs12_export_to_file($certificate,$filename,$pkey, $privateKeyPass);
That worked file, so values of $certificate and $privatekey / $pkey seems to be ok.
Any idea? Whats wrong?
I have a video streaming website which also allows users to download videos. This runs over a download script that loads the videos id on the server and initiates a direct file transfer.
Now I want to put another URL in front of it instead of having the direct file transfer. I tried to make a mod_rewrite rule, but it causes a loop and redirects on that URL forever. Its a link shortening service which allows monetarization.
So, how do I archieve this? Is it possible to archieve it with a mod_rewrite rule?
Trying the mod_rewrite rule, realizing I can't change the base_url variable in PHP because it would not find the file anymore.
$vid = intval($_GET['id']);
$label = intval($_GET['label']);
$sql = "SELECT * FROM video WHERE VID = ".$vid." LIMIT 1";
$rs = $conn->execute($sql);
$formats = $rs->fields['formats'];
$server = $rs->fields['server'];
$formats_arr = explode(',', $formats);
if ($server != '') {
$sql = "SELECT * FROM video v, servers s WHERE v.VID = ".$vid." AND v.server = s.video_url LIMIT 1";
$rs = $conn->execute($sql);
$video_root = $rs->fields['video_url'];
}
if (!$video_root) {
$video_root = $config['BASE_DIR']."/media/videos";
}
foreach ($formats_arr as $format) {
$f = explode('.', $format);
if ($label == $f[1]) {
if ($f[0] >= 481) {
$condition = $new_permisions['hd_downloads'];
} else {
$condition = $new_permisions['sd_downloads'];
}
$file = $video_root.'/h264/'.$vid.'_'.$f[1].'.'.$f[2];
$file_name = $vid.'_'.$f[1].'.'.$f[2];
break;
}
}
if ($condition == 1) {
ini_set('memory_limit', '-1');
if (!$server) {
if (file_exists($file) && is_file($file) && is_readable($file)) {
$conn->execute("UPDATE video SET download_num = download_num+1 WHERE VID = ".$vid." LIMIT 1");
#ob_end_clean();
if(ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Cache-control: private');
header('Pragma: private');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-Length: ' .filesize($file));
readfile($file);
exit();
} else {
VRedirect::go($config['BASE_URL']. '/error');
}
} else {
$conn->execute("UPDATE video SET download_num = download_num+1 WHERE VID = ".$vid." LIMIT 1");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: chunked');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
$stream = fopen('php://output', 'w');
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_READFUNCTION, function($ch, $fd, $length) use ($stream) {
return fwrite($stream, fread($fd, $length));
});
The download button should open URL/download.php with my link shortener URL in front of it, so it will load and redirect to the file download URL.
Recently moved a site over to a new server and now for some reason the download page is no longer downloading the purchased files.
When the download page is reached it is simply blank. I have changed the filename directory to use home/mastetu8 instead of home/mastvoic which was the last directory. Any idea on why the page is blank when trying to download?
Here is the download_process.php file currently running this piece:
<?php ob_start(); ?>
<?php require_once('../Connections/admin.php'); ?>
<?php
$orders_id = $_GET['orderid'];
$id = $_GET['id'];
mysql_select_db($database_admin, $admin);
$query_rsOrdersDetail = "SELECT * FROM orders_detail LEFT JOIN media ON orders_detail.product_id = media.sortorder WHERE orders_detail.orders_id = '$orders_id' AND orders_detail.id = '$id'";
$rsOrdersDetail = mysql_query($query_rsOrdersDetail, $admin) or die(mysql_error());
$row_rsOrdersDetail = mysql_fetch_assoc($rsOrdersDetail);
$totalRows_rsOrdersDetail = mysql_num_rows($rsOrdersDetail);
// CHECK DOWNLOAD COUNT
if ($row_rsOrdersDetail['downloadcount'] <= 3) {
$filename_hires = '/home/mastetu8/public_html'.$row_rsOrdersDetail['filename_hires'];
if (file_exists($filename_hires)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filename_hires));
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_hires));
ob_clean();
flush();
readfile($filename_hires);
// UPDATE DOWNLOAD COUNTER
$downloadcount_new = $row_rsOrdersDetail['downloadcount'] + 1;
mysql_select_db($database_admin, $admin);
mysql_query("UPDATE orders_detail SET downloadcount='$downloadcount_new' WHERE id = '$id' AND orders_id = '$orders_id'", $admin) or die(mysql_error());
}
}
?>
When using computer files are downloaded normally.
Problem start on android browsers.
When we download a file from android default browser, the file is downloaded but it is of 0.00 bytes, so not technically present there(corrupt file).
When we download file from any third party application like or opera it gives error that "file could not be downloaded." not the header error. And files could be downloaded via UC Browser and Chrome and Firefox. But still gives the error in default browser.
Here is the code I am using:
<?php
require 'php/db.php';
if(isset($_POST['file_id'])&&!empty($_POST['file_id'])){
download_file($_POST['file_id']);
}
function download_file($id){
global $con;
$id = mysqli_real_escape_string($con,htmlentities($id));
$file="SELECT file_name,file_title,file_size,down FROM files WHERE file_id= $id";
$result = mysqli_query($con,$file);
$row = mysqli_fetch_assoc($result);
$name = $row['file_name'];
$title = $row['file_title'];
$size = $row['file_size'];
$ext = strtoupper(ext($name)); // Function defined bellow
$down = $row['down'];
$newname = $title.'.'.$ext;
$olddir = "files/".$name;
$down++;
if(is_file($olddir)) {
$update_down = "UPDATE files SET down = $down WHERE file_id = '$id'";
$update_down_result = mysqli_query($con,$update_down);
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($olddir)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$newname.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.$size); // provide file size
header('Connection: close');
readfile($olddir);
exit();
}else header("Location: index.php?msg=Sorry!+File+could+not+be+downloaded");
}
function ext($name){
$rut = strrev($name);
$erut = explode('.', $rut);
return strrev($erut[0]);
}
We give file id to this function and it downloads the file on PC.
Can anyone tell me how to remove the error? So that users can download files from their android phones too.
Probably $size == 0;
$size = $row['file_size'];
...
$olddir = "files/".$name;
change to
$olddir = "files/".$name;
$size = filesize($olddir);
And change
else header("Location: index.php?msg=Sorry!+File+could+not+be+downloaded");
to
else header("Location: index.php?msg=Sorry!+File+could+not+be+found+on+server: " . $olddir);
I got the solution.
Mainly I changed two things:
Used GET method instead of Post Method.
Used Flush and ob_clean functions to clear the buffer.
New code for downfile.php is like this:
<?php
require '../php/db.php';
ob_start();
if(isset($_GET['file_id'])&&!empty($_GET['file_id'])){
download_file($_GET['file_id']);
}else die("There was an error in downloading file. Please try again later.");
function download_file($id){
global $con;
$id = mysqli_real_escape_string($con,htmlentities($id));
$file="SELECT file_name,file_title,file_size,down FROM files WHERE file_id= $id";
$result = mysqli_query($con,$file);
$row = mysqli_fetch_assoc($result);
$name = $row['file_name'];
$title = $row['file_title'];
$ext = ext($name);
$down = $row['down'];
$newname = $title.'.'.$ext;
$size = $row['file_size'];
$down++;
if(is_file($name)) {
$update_down = "UPDATE files SET down = $down WHERE file_id = '$id'";
$update_down_result = mysqli_query($con,$update_down);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$newname.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.$size);
ob_clean();
flush();
readfile($name);
exit;
}else header("Location: index.php?msg=Sorry!+File+could+not+found!");
}
function ext($name){
$rut = strrev($name);
$erut = explode('.', $rut);
return strrev($erut[0]);
}
?>
Through this code I am able to download files in android browsers too.
Hope this may help. :)
Here is the code I am using to try and retrieve an image from a database:
<?php
if($id)
{
//please change the server name username and password according to your mysql server setting
$mysql_server="localhost";
$mysql_username="myuser";
$mysql_password="mypass";
$mysql_database="mydb";
//connect to database using above settings
#MYSQL_CONNECT("localhost",$mysql_username,$mysql_password);
#mysql_select_db("mydb");
//select the picture using the id
$query = "select bin_data,filetype from todo where id=$id";
//execute the query
$result = #MYSQL_QUERY($query);
//get the picture data which will be binary
$data = #MYSQL_RESULT($result,0,"bin_data");
//get the picture type. It will change according to file extension it may be either gif or jpg
$type = #MYSQL_RESULT($result,0,"filetype");
//send the header of the picture we are going to send
Header( "Content-type: $type");
//send the binary data
echo $data;
};
?>
Instead of displaying the requested image, it displays this icon: (not sure what you call it)... http://i.imgur.com/bo6Jg.png
Here are all the columns in my table: http://i.imgur.com/PuWvl.png
I'm pretty positive I'm doing everything right...not sure what's going on. Help anyone? Thanks in advance!
IMO only constants should be uppercase (tho I gladly did not know they could be upper),
Anyway Try this:
<?php
$file_not_found = '../not_found_image.jpg';
//Get the id param from GET else null
$id = (isset($_GET['id']) && is_numeric($_GET['id']))?$_GET['id']:null;
if($id != null) {
$mysql_server="localhost";
$mysql_username="myuser";
$mysql_password="mypass";
$mysql_database="mydb";
//Connect to database using above settings
mysql_connect($mysql_server,$mysql_username,$mysql_password) or die(mysql_error());
mysql_select_db($mysql_database) or die(mysql_error());
//Select the picture using the id
$query = "SELECT `bin_data`, `filetype` FROM todo WHERE id=".(int)mysql_real_escape_string($id)." LIMIT 1";
//Execute the query
$result = mysql_query($query);
//Found
if(mysql_num_rows($result)==1){
//Get the picture data which will be binary
$data = mysql_result($result,0,"bin_data");
//Get the picture type. It will change according to file extension it may be either gif or jpg
$type = mysql_result($result,0,"filetype");
//Send the header of the picture we are going to send + cache
header('Cache-Control: private, max-age='.(60*60*24*365));
header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*365));
header("Pragma: private");
header('Content-Type: '.$type);
header('Content-Length: ' . strlen($data));
//Send the binary data
echo $data;
}else{
//Not found
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file_not_found));
readfile($file_not_found);
}
}else{
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file_not_found));
readfile($file_not_found);
}
?>
Try this..
header("Content-type: image/gif");
$expires = 60*60*24*14;
header("Pragma: public");
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
error_reporting(0);
require_once "class/dbconn.php";
$id=$_GET['id'];
$sql="select thumbimage from image where img_id=$id";
$rs=mysql_query($sql) or die (mysql_error());
$row =mysql_fetch_array($rs,MYSQL_BOTH);
$data = $row[0];
print $data;