Retrieving image from database - image not displayed - php

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;

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";
}
?>

Opening pdf with mysql and php

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";
}
}

Blank Download Page [PHP]

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());
}
}
?>

Not able to download files with php in android browsers

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. :)

download php is always damaged

I have a download script written in PHP. My view file script links to the ids and then selects all the data that matches the ID.
The data is then used to download the photo. Does it matter that my photo is in a folder? It is moved to a folder and then the directory is uploaded to the MYSQL database.
The code at the moment now allows some files to download perfectly and then the majority to be damaged. Any reason why?
Mysql table info...
$cool = $_GET['id'];
$sql = "SELECT id, type, name, size FROM upload WHERE id='$cool'";
$result = mysql_query($sql, $db);
$data = mysql_result($result, 0, "id");
$name = mysql_result($result, 0, "name");
$size = mysql_result($result, 0, "size");
$type = mysql_result($result, 0, "type");
header("Content-type: $type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
header("Content-Description: PHP Generated Data");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile($name);
exit();
This happens because PHP send some information after you echo the data, the solution to this is to stop processing right after you echoed the data, for this add exit(); right after echo $data.

Categories