Download Blob file with php ( mysql ) - php

I have a MySQL database where I have a table call for example "ALL" can contain a blob files.
In the table i have stored the: size of the file, the type, the name and the content.
The problem come when i try download the blob file.
This is my script:
<?php
$connection = mysqli_connect("localhost","user","password",dbname)
or die('Database Connection Failed');
mysqli_set_charset($connection,'utf-8');
$query = "SELECT * " ."FROM ALL WHERE id = '25'";
$result = mysqli_query($connection,$query)
or die('Error, query failed');
list($id, $user_made, $title, $category, $sub_category, $text, $type, $date, $time, $namefile1, $typefile1, $sizefile1, $contentfile1, $namefile2, $typefile2, $sizefile2, $contentfile2, $namefile3, $typefile3, $sizefile3, $contentfile3) = mysqli_fetch_array($result);
echo $id . $namefile1 . $typefile1 . $sizefile1;
header('Content-Length: '.$sizefile1);
header('Content-Type: '.$typefile1);
header('Content-Disposition: attachment; filename="'.$namefile1.'"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
ob_clean();
flush();
// echo $contentfile1;
mysqli_close($connection);
exit;
?>
But the page output only the echo of "$contentfile1" and "$id . $namefile1 . $typefile1 . $sizefile1".
Everyone can help me?
Thanks

Add this code before ob_clean.
$context = stream_context_create();
$file = fopen($filename, 'rb', FALSE, $context);
while(!feof($file))
{
echo stream_get_contents($file, max_bytes_to_read);
}
fclose($file);
You can get more information about stream_get_contents at http://php.net/manual/en/function.stream-get-contents.php

Related

php script to convert csv to pdf

I'm going to modify the below php script such that it downloads the database as a .pdf file rather than in a .csv format. How should I do that? Currently when this script is called, the database will be downloaded as a .csv file. The database is defined in directadmin.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'db.php';
define("tableStuff", "stuff");
define("tableUser", "user");
define("ERR", '{"status":1}');
define("INVALID", '{"status":2}');
define("rowUserId", "user_id");
define("rowRegDate", "reg_date");
define("rowStuffName", "stuff_name");
define("rowPurchaseDate", "purchase_date");
define("rowStuffCount", "stuff_count");
define("rowStuffDescription", "stuff_description");
define("rowPicUrl", "pic_url");
define("rowUserName", "user_name");
//**********************************************************************
$mysqli = mysqli_connect(DBIP, DBUN, DBPW, DBNAME);
if ($mysqli->connect_errno) {
echo ERR;
die;
}
mysqli_set_charset($mysqli, "utf8");
$result = $mysqli->query("SELECT ".rowStuffName.",".rowStuffCount.",".rowStuffDescription.",".rowPurchaseDate.",".tableStuff.".".rowRegDate.",".rowUserName." FROM " . tableStuff .",".tableUser.
" WHERE " . tableStuff.".".rowUserId . " = " . tableUser.".".rowUserId);
if ($result->num_rows > 0) {
$array = array();
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
$array[] = $row;
}
header('Content-Encoding: UTF-8');
header('Content-Type: application/csv; charset=utf-8' );
header(sprintf( 'Content-Disposition: attachment; filename=stuff.csv', date( 'dmY-His' ) ) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
//echo pack("CCC",0xef,0xbb,0xbf);
$title = array("نام کالا","تعداد (مقدار)","توضیحات","زمان ثبت","نام فرد ثبت کننده");
$out = fopen("php://output", 'w');
//fputs($out,"\xEF\xBB\xBF");
fputcsv($out, $title,"\t");
foreach ($array as $data)
{
fputcsv($out, $data,"\t");
}
fclose($out);
} else {
echo INVALID;
}
mysqli_close($mysqli);
I am late,but i am using FPDF to generate all PDF files,It includes a built in example of making PDF with tables from CSV file,I just changed the source of CSV file.It is super easy.

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

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 script to update mysql table on click of link

I'm new to php and need help.
My link as below:
//create a path to download
echo '<a download="Final_File_'.$filenames.'" name="save" href="'.$DownDir. "/".$filenames.'" target="_blank"><img src="images/Save File.png"/></a>';
//Query
$Query = 'UPDATE `tbl_download_log` SET `User_Id` = `User_Id`, `path` = `$DownDir. "/".$filenames`';
Saves a file on the click of the ImageLink and need to update the a table in MySQL DB named tbl_download_log with the 'user ID' & 'Download link' at the same time.
I established the connection and got the user ID as well.
Please help me to update both the thing in db table.
Updating new script in it.
<?php
$DownDir = "http://localhost/SGA-INTRANET/".$kmsroot. "/". $user. "/". $bu. "/". $client. "/". $project."/Final";
$filenames = "file.xlsx";
$pathDown1 = $DownDir. "/".$filenames;//download path
//using download functionality of HTML 5
echo '<a download="Final_File_'.$filenames.'" name="save" href="'.$pathDown1.'?id='.$name.'&filepath='.$pathDown1.'" target="_blank"><img src="images/Save File.png" title="Download the file"/></a>';
?>
<?php
$ide = $_GET['id'];//EmployeeID
$file = $_GET['filepath'];// Path
if(isset($ide) && isset($file))
{
if(file_exists($file))
{
//save log to DB table 'tbl_km_file_download'
$mysqli = new mysqli("localhost", "USERNAME", "PASSWORD", "DBNAME");
$mysqli->query("INSERT INTO `tbl_km_file_download` (`name`, `filename`) VALUES ('$ide', '$file')");
}
}
?>
which is downloading files but not updating the DB table.
Please see the images.
Please help.
You can pass data through the href with query strings.
Example
echo 'CLICK THE LINK';
$file should be a root-relative path, starting with a /.
Then in download.php:
<?php
$id = $_GET['id'];
$file = $_GET['file'];
if(isset($id) && isset($file)) {
if(file_exists($file)) {
//connect to database .... (I show it with PDO)
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', USERNAME, PASSWORD);
$stmt = $db->prepare("INSERT INTO `tbl_download_log` (`User_Id`, `path`) VALUES (?, ?)");
$stmt->execute(array($id, $file));
//download the file....
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
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($file));
ob_clean();
flush();
readfile($file);
} else echo "The file does not exist.";
} else echo "An error occurred.";
Hope this helps.

Export csv to any other program user has on his system

I want to export my db data to CSV or asking user "Open with his local supporting program".
Exporting to csv I could understand using this code:
<?php
header("Content-type: text/csv; charset=UTF-8");
header('Content-Disposition: attachment; filename=Export.csv');
//connection
$con = mysql_connect('localhost', 'root', '');
if(!$con){
echo "Error connection";
}
//select db
$select_db = mysql_select_db('country', $con);
if(!$select_db){
echo "Error to select database";
}
mysql_set_charset("utf8", $con);
//Mysql query to get records from datanbase
$user_query = mysql_query('SELECT * FROM countries');
//While loop to fetch the records
$contents = "ccode,country\n";
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['ccode'].",";
$contents.=$row['country']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
?>
How 2nd part could be managed? Showing option to open with local installed program?
Above code is correct?
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="your_file_name.csv"');
header('Content-Transfer-Encoding: binary');
This will cause the browser to display the dialog box to Save / Open the file.
You should also consider a) switching to mysqli_ or PDO and b) using PHP's built-in csv functions, e.g.
ob_start();
$f = fopen('php://output', 'w');
// $results comes from mysqli_ functions
foreach ( $results as $k => $v ) {
fputcsv($f, $v);
}
$output = ob_get_contents();
ob_end_clean();
echo $output;

Categories