write ZIP with PHP from MSSQL IMAGE field retrieved as BINARY STREAM - php

I want to retrieve a ZIP file with PHP from a MSSQL database wich is stored in a IMAGE field.
In this part i make a connection using sqlsrv, send a query, and move to the first row and get the first field in BINARY encoding.
$conn = sqlsrv_connect($sql['s'],array('Database'=>$sql['db'],'UID'=>$sql['usr'],'PWD'=>$sql['pwd']));
$q = 'SELECT TOP 1 FileContent
FROM dbo.tblDocumentContent
WHERE FileContent IS NOT NULL
ORDER BY CreateDate DESC';
$res = sqlsrv_query($conn, $q);
sqlsrv_fetch($res);
$zip = sqlsrv_get_field($res,0,SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
At this point the zip is retrieved as a resource stream and here i get stuck.
When i set the headers and output the content, the browser downloads the zip.
header("Content-type: application/zip, application/octet-stream");
header("Content-Disposition: attachment; filename=test.zip;");
fpassthru($zip);
This works like a charm, the zip works perfect.
But what i want is to open the zip serverside without the user having to dowload it.
So when i just try to write the content to a file:
$file = fopen('test.zip', 'a');
fwrite($file, fpassthru($zip));
fclose($file);
It can't be opened. I figured that when the browser downloads the given content, it encodes it someway. Alltrough i can not figure out how to do that while writing it to a file.
If someone has any solutions to write the resource stream to a file on the server side in the proper way, that would be great.

This should solve the problem:
$file = fopen('test.zip', 'w');
while (!feof($img)) {
$chunk = fread($img, 1024);
fwrite($file, $chunk);
}
fclose($img);
fclose($file);

Related

Save PDF as a blob in a database using PHP?

I have a PDF file on my server that I want to select and transform into a blob for insertion into my database (using an INSERT INTO command). My first problem is getting hold of the PDF using PHP. I know it is done with the file_get_contents() function, but I do not understand what parameters it needs.
$fp = fopen($fileLocation, 'r');
$content = fread($fp, filesize($fileLocation));
$content = addslashes($content);
fclose($fp);
You can save the $content to blob field in mysql

Generate/Download of CSV throws a Connection error PHP

So the process that I have goes like this. A user can pick a date range to view the data that he wants/needs. A Download is then available if he wants to download the file.
When doing a wide range the page throws off a connection error.
Firefox - The connection was reset
Chrome - No Data Received
The code that I use to generate the CSV is
<?php
$res = // the array generated by a mysql query
$text=strtotime("Now");
$filesave=fopen('Downloads/CallLogs'.$text.'.csv','w');
foreach ($res as $display)
{
fputcsv($filesave,$display);
}
//Force download the file. you can correct me if this is the improper way of doing it :)
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="CallLogs'.$text.'.csv"');
$fp = fopen("Downloads/CallLogs".$text.".csv", "r");
fpassthru($fp);
fclose($fp);
?>
Thanks in advance...

PHP Export Excel to specific Path?

Is it possible to export a PHP MySQL Excel sheet to a specified path such as USB Flash Drive.
Its because I'm using php as Point of Sale and all What i want now is once you click on a Button- it will collects records from MySQL database and exports it as excel or csv file to a USB Flash Drive.
I've tried to Google it out, but I can't seem to find anything.
Thank You.
You need to write the file. To write to usb drive you just need to specify correct file path. If you're on *nix it would be like /media/USB/ on linux or /Volumes/USB/ on Mac. For Windows it would be like F:/.
so rough example is like
$a = array('1','2','3'); //This is imaginable row from MySQL
$f = fopen('F:/mycsv.csv', 'w');
fputcsv($f, $a);
fclose($f);
Manual for fputcsv is here.
If needed, you can ask user for a file path in any way supported by your application.
Not a simple process to save it as excel, but relatively straightforward to write a csv.
$temp = tempnam(sys_get_temp_dir(),'tmp');
$handle = fopen($temp,'w');
$query = $pdo->prepare("select * from table");
$query->execute();
$row=$statement->fetch();
$keys=array_keys($row);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export_'.date('dmY').'.csv');
fputcsv($handle,$keys);
while($row){
fputcsv($handle,$row);
$row=$statement->fetch();}
echo file_get_contents($temp);
fclose($handle);
This creates a temporary file in your temp folder, you write the csv to that and then give it csv headers and echo it out which gives the user a save file box.
I call $row once before the loop to get the table columns with array_keys and output those first and then loop through with a while calling $row=$statement->fetch() at the end of the loop.

inserting/reading blob data from php

I am using the following scripts to test inserting and then reading blob data.
insertion script:
include('session.php');
$provider =$_POST['provider_id'];
$trd_period =$_POST['trading_period_month'];
$pdf_statement =stream_get_contents(fopen($_FILES['pdf_statement']['tmp_name'], 'rb'));
$pdf_statement_clean=addslashes($pdf_statement);
$insert="update rd_provider_statement
set pdf_statement='".$pdf_statement_clean."', creation_user_id='SCO'
where provider_id='".$provider."' and trading_period_month='".$trd_period."'";
mysql_query($insert);
mysql_query("COMMIT");
echo mysql_error();
Download Script:
include('session.php');
//Gather Post Variables
$TP_Month =$_POST["trading_period_month"];
$provider =$_POST["provider_id"];
$TP_format =substr($TP_Month, 0, 7);
//Download Statement
$sql_qry="select *
from rd_provider_statement
where provider='".$provider."' and trading_period_month='".$TP_Month."'";
$sql_err_no=sql_select($sql_qry,$sql_res,$sql_row_count,$sql_err,$sql_uerr);
$row = mysql_fetch_assoc($sql_res);
$bytes =stripslashes($row['pdf_statement']);
header("Content-type: application/pdf");
header('Content-disposition: attachment; filename="'.$provider.'statement'.$TP_format.'"');
print $bytes;
However, when the file is downloaded it cannot open on the grounds that it is not a supported format. I use the basis of the script on another page to download blob data from the database however the insertion into the database here is done by a mysql procedure and not PHP. I think it is my insertion script that is causing the problem.
try using mysql_real_escape_string() instead of addslashes(). it might fix you problem.
For debugging, you might calculate the md5() of the string before inserting into DB and then after retrieving it. I bet you're going to get different hashes, meaning you're not inserting it correctly and your binary data gets corrupted when inserted into the DB.
Side notes:
don't use inserts like that, use binding - How to bind SQL variables in Php?
check for errors and STOP, dont simply echo them(i hope you're doing this in your production code)
Generally you wouldn't want to have any output code before your http header description. See http://php.net/manual/en/function.header.php
Either store the filename and other file information in a session then just access them in another page.
A few things that you need to check:
max_allowed_packet in my.ini should be equal or higher than the file size that you're expecting to store in the database
check to see if the data type that you selected fits the file that you will store. There's tiny blob, blog, medium blob and long blob. You might want to try the largest which is long blob.
I'm not sure about this one but did you already check if file_get_contents works:
mysql_real_escape_string(file_get_contents($file))
Here's my alternative answer.
First the update query:
Prepare the file (assuming that your file is not a binary file):
$tmpName = $_FILES["pdf_statement"]["tmp_name"];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$insert="update rd_provider_statement
set pdf_statement='".$data."', creation_user_id='SCO'
where provider_id='".$provider."' and trading_period_month='".$trd_period."'";
DOWNLOAD:
enter code here
$sql_qry="select provider_id, pdf_statement
from rd_provider_statement
where provider='".$provider."'
and trading_period_month='".$TP_Month."'";
$sql_err_no=sql_select($sql_qry,$sql_res,$sql_row_count,$sql_err,$sql_uerr);
$row = mysql_fetch_assoc($sql_res);
$name=$row['provider_id'];
$file=$row['pdf_statement'];
header("Content-Disposition: attachment; filename=\".$name_statement.$TP_format.\";" );
echo $file;
Hope it helps =)

Export mySQL to excel or csv

I'm no php expert (a mere beginner) but need some help!
After hours searching Google and trying out about 100 different scripts, I finally found one that does what I need - almost.
Basically, my site has a button marked 'Export to Excel'. Visitor to site clicks button and a download begins containing all data from a specified table.
I found this on here - PHP code to convert a MySQL query to CSV
which does exactly what I want except the user sees the following error when trying to open the file:
Error - 'The file you are trying to open, 'export.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Wo you want to open the file now?'
User clicks 'Yes' and file opens with all data! Brilliant! Except users will not open the file with this error.
I would be very grateful if someone knows a way to fix this.
Many thanks
TT
Or, you could just change the script in the above solution to return a file with the .csv extension. .csv files are associated with Excel, so they should open directly.
Ok, this results from a feature specified by Excel 2007 called Extension Hardening. You can turn it off, but that can only be done client-side. If you click "OK" or "Yes" the file should open anyway. Check this blog post for more info.
EDIT: What this means is that Excel is finding that the file is of a different type (say HTML or CSV) that what is specified by the file extension. Therefore Excel wants to warn you that this file is not what it says it is. Unless you are going to create native Excel files on the server then prompt the user to download them, there is no getting around this error except for each user to turn off Extension Hardening on their own computer.
if you make the first letters “ID” of a text file Excel incorrectly
assumes you are trying to open an SYLK file.
Meaning if the first row & column value is "ID", Excel will throw this warning. Just change it from "ID" to anything else.
Credit: http://alunr.com/excel-csv-import-returns-an-sylk-file-format-error/
Dim objXL As Excel.Application
Dim objWkb As Excel.Workbook
Set objXL = New Excel.Application
'turn off excel warnings
objXL.DisplayAlerts = False
'Open the Workbook
Set objWkb = objXL.Workbooks.Open(fpath)
functions sendFile($filename,$content_type="application/ms-excel") {
header('Content-type: '.$content_type);
header('Content-disposition: Attachment; filename=' . $filename);
readfile($filename);
}
I had the same problem so I looked at the following link: PHP code to convert a MySQL query to CSV
I modified one of the answers to get the headers to work.
include('DBFILE.PHP');
$select="SELECT * FROM SOMETable";
$result = mysqli_query($conn, $select);
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
//This is what I changed...
$headers ="";
while ($property = mysqli_fetch_field($result)) {
$headers.= $property->name.",";
}
$headers.="\n";
//////
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
I Tested this and it works like a charm, you just need to add your db connection or include the db.php file that you have.
you can change the name of the file if you edit the following line
header('Content-Disposition: attachment; filename="export.csv"');
Change export to what ever name you like.

Categories