error while downloading file in PHP - php

while downloading file im getting this error. specially pdf files.
and also program like download manger doesn't work on the downloading.
v?—x¢b(‏°®ه– ç‏zٍڈà÷µï½zTَکêùQïىxùSَ–‏jîآ·×Yï¹oف5KK÷¾oصتمح+¾¦œ:و†ƒloوnأ"گ ±Oّ•زـ¦§w8^uLٹé†-ئûpfچâ+أجشƒœر د؛-ںe•ؤ…¬RH¦ hْDyے#½=#'X'§¾ذXœtz”†رص0âLوٍ›“ء²{÷ڈے ½}f؛ِâB¦ک­ژ¯“كگyeطPeüpy,¥¼تِŒً•MR±wگCي¢âٹ‘¬}Fzى3¢e¾NAو^4è¬{j=¤ر³جسâل<¶–5Mz&#+­MYN1ُ¨Cںq)زêذش£M nj‍]T‡à*×h0ï3D¤­6غإQ.µg¬€ء¥w«ي|م+s“çكûmٍاe¯Œغ½وؤ~لà…½ں$/‡ھ(!·#‡]µظtحîز4»CQeں[°ظ5گ+è’ہù4›MQd™#ں|‡فژd؟×ë×F*xز‘ ¹’پ÷i·?ù×ـسخ½Mأ}ق¸َOe$ِ à'ظgءl”ƒ=fRن(rإهـPy¨2ش2ج:طQî49œt رA3kfفذ’){¯'7ذE=»نx¾ةLb|‘شاـ×s ل‡ةأجô‰—ثSùy¦y†uھc>‍ا/’›Zç9Vٍ·بش&¸ةq“s؟Yعlzگïگ_v¼ئ؟!؟د h=لّ’ےJ‏تْ…£ںبb÷U;Lآڑ›eڑƒ¨}كFپ ں›Uنvi>“]¤vçW†•Bڑˆˆ´!ج=¥4†é1حز ہحٹ‚é?“ل¢qع¬ ض4‹فلtڑgؤbوT§ةŒEچ8“س©#ôںآ‹EW9—ھr ‘8ژ§¦z$»±¸SW •¨xضث؛i›©سؤ™:pا¾YهسaکؤvC«صژkœچ “ژr\îW"Tùؤ'œ¥<غàû<§«،«ئ¶ —ًيFل¥رکً³ظ(WVتG{i®> stream xœه]ëڈeإqXXVثs1ث‚¹ ;†¹ôûAâDٹEت7[Hùùd'N"ضر’ے_JUWَُô¹sg¦w±#ygخمVWuWWW?~Oâ(صAàü‏ةف¯çüك»éد‡ےxW‏ë®4ٌ£;Hkز؟ے_ؤƒSر~ü÷»ےQ‍pئ¨C0؛{,=ƒ=َù‰ég”qً?™ïH،l{[:گJ›‏Uي¢؛ٍص,أوm)¤>ٌ6ف‍ے°R:^ùêî[ثٹ3¢¾m…ƒضŒ‡ إVeززF{{0BM‍ˆڑں°îùخVيئ[ّ هYPüG6Eàغn{[£´Rآدù•د¥·ءىفس¾¸÷‍‹~÷=ِ/
here is my php code for downloading
<?php
$company =$_GET['company'];
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = intval($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT mime, name, size, data
FROM $company
WHERE id = $id";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
echo $row['data'];
}
else {
echo 'Error! No image exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
#mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>

use BLOB in MySQL to prevent that the data is changed due to the encoding (there might be encoding issues which produce your errors, saving as BLOB is binary safe)
related to Binary Data in MySQL
it may be better to store a link as file reference in the database instead of saving the actual content of the file and retrieve the files using file_get_contents and other related functions to get the mimetype (or finfo) ...
take a look at Trying to download Blob via PHP / MySQL and http://www.sitepoint.com/forums/showthread.php?693871-Problem-using-PHP-to-pull-binary-files-from-a-BLOB-field-in-MYSQL

Try flushing the output buffer immediately before you start setting headers with ob_end_clean, and then exiting immediately after the echo. Take a look at the section of the PHP book on Output Control.
The other possibility is that you are running out of memory when attempting to echo the data, and the error is getting obfuscated by all the preceding binary. Try splitting the binary in to smaller chunks (substr is binary safe), iterating over them and returning them to the output buffer.

Related

http force headers not working with above < 2GB files

I have a script which is used to download large files in pdf and media format. I can't download it it gives http internal error sometimes it give 500 internal server error sometimes.
<?php
//The directory where the download files are kept - keep outside of the web document root
$strDownloadFolder = "uploads/";
//If you can download a file more than once
$boolAllowMultipleDownload = 0;
// 1. Create a database connection
//connect to the DB
$resDB = mysql_connect("localhost", "root", "");
mysql_select_db("downloader", $resDB);
if(!empty($_GET['key'])){
//check the DB for the key
$resCheck = mysql_query("SELECT * FROM downloads WHERE downloadkey = '".mysql_real_escape_string($_GET['key'])."' LIMIT 1");
if($resCheck == FALSE) { echo "QUERY FAILED: " . mysql_error(); }
$arrCheck = mysql_fetch_assoc($resCheck);
if(!empty($arrCheck['file'])){
//check that the download time hasnt expired
if($arrCheck['expires']>=time()){
if(!$arrCheck['downloads'] OR $boolAllowMultipleDownload){
//everything is hunky dory - check the file exists and then let the user download it
$strDownload = $strDownloadFolder.$arrCheck['file'];
if(file_exists($strDownload)){
//get the file content
$strFile = file_get_contents($strDownload);
//set the headers to force a download
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"".str_replace(" ", "_", $arrCheck['file'])."\"");
//echo the file to the user
echo $strFile;
//update the DB to say this file has been downloaded
mysql_query("UPDATE downloads SET downloads = downloads + 1 WHERE downloadkey = '".mysqli_real_escape_string($_GET['key'])."' LIMIT 1");
exit;
}else{
echo "We couldn't find the file to download.";
}
}else{
//this file has already been downloaded and multiple downloads are not allowed
echo "This file has already been downloaded.";
}
}else{
//this download has passed its expiry date
echo "This download has expired.";
}
}else{
//the download key given didnt match anything in the DB
echo "No file was found to download.";
}
}else{
//No download key wa provided to this script
echo "No download key was provided. Please return to the previous page and try again.";
}
?>
Since http force headers are not working for larger files... I wanna use href with download attribute so when user clicks on it it should have direct encrypted link! with token or limited session!
file_get_contents reads the entire file into memory. If the file is larger than the available memory, it fails.
Instead you can read the file contents directly to the output stream:
//read whole file into memory, whoops
//$strFile = file_get_contents($strDownload);
//set the headers to force a download
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"".str_replace(" ", "_", $arrCheck['file'])."\"");
//read file to output stream
readfile($strDownload);
http://php.net/manual/en/function.readfile.php

how to convert page to pdf in php

I have an html page like JsFiddle and I want convert this in pdf, i can't create the line to line pdf because the page is dinamically create, I use php for calling a fiel that connect to mysql and fill a template file like.
$_POST['IdQuestionario']=5;
$_POST['IdUtente']=10001;
$_POST['Visualizza']=true;
$_POST['IdImpianto']=1;
$_POST['Stampa']=true;
$_POST['TipoImpianto']='grande';
ob_start();
ob_clean();
require_once 'intro.php';
$tbl=ob_get_clean();
$html.=$tbl;
I'm trying with tcpf, mpdf , jsPDF but i cant obtain a discrete output because I use colgroup for table. anyone say me a method for render the page,if is possible whitout install software on server.
There a few that i know of - some have problems with tables, I would avoid DOMPDF - known issues with tables.
There's one that's recommended from cvision; i don't have a code sample, but you can download it free and even sample it online.
There's also a php-pdf product available from muhimbi (a little lesser-known!, but i think it's free)
<?php
// Include the generated proxy classes
require_once "documentConverterServices.php";
// Check the uploaded file
if ($_FILES["file"]["error"] > 0)
{
echo "Error uploading file: " . $_FILES["file"]["error"];
}
else
{
// Get the uploaded file content
$sourceFile = file_get_contents($_FILES["file"]["tmp_name"]);
// Create OpenOptions
$openOptions = new OpenOptions();
// set file name and extension
$openOptions->FileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$openOptions->OriginalFileName = $_FILES["file"]["name"];
// Create conversionSettings
$conversionSettings = new ConversionSettings();
// Set the output format
if(isset($_POST["outputFormat"]))
{
$conversionSettings->Format = $_POST["outputFormat"];
} else {
$conversionSettings->Format = "PDF";
}
// Set fidelity
$conversionSettings->Fidelity = "Full";
// These values must be set to empty strings or actual passwords when converting to non PDF formats
$conversionSettings->OpenPassword="";
$conversionSettings->OwnerPassword="";
// Set some of the other conversion settings. Completely optional and just an example
$conversionSettings->StartPage = 0;
$conversionSettings->EndPage = 0;
$conversionSettings->Range = "VisibleDocuments";
$conversionSettings->Quality = "OptimizeForPrint";
$conversionSettings->PDFProfile = "PDF_1_5";
$conversionSettings->GenerateBookmarks = "Automatic";
$conversionSettings->PageOrientation="Default";
// Create the Convert parameter that is send to the server
$convert = new Convert($sourceFile, $openOptions, $conversionSettings);
// Create the service client and point it to the correct Conversion Service
$url = "http://localhost:41734/Muhimbi.DocumentConverter.WebService/?wsdl";
$serviceClient = new DocumentConverterService(array(), $url);
// If you are expecting long running operations then consider longer timeouts
ini_set('default_socket_timeout', 60);
try
{
// Execute the web service call
$result = $serviceClient->Convert($convert)->ConvertResult;
// Send the resulting file to the client.
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"convert." . $conversionSettings->Format . "\"");
echo $result;
}
catch (Exception $e)
{
print "Error converting document: ".$e->getMessage();
}
}
?>
Also, you could investigate 'Snappy' (has dependencies)
You can try WKHTMLTOPDF.
Here is a Stackoverflow Thread on how to use it with PHP.
How do I get WKHTMLTOPDF to execute via PHP?
And here is a wrapper for PHP
https://github.com/mikehaertl/phpwkhtmltopdf
MPDF one of best library to convert pdf, try it
MPDF link : http://www.mpdf1.com/mpdf/index.php
Example link : http://mpdf1.com/common/mpdf/examples/

Audio files to be stored into database

Prior to this link:What is the best way to store media files on a database?
The answer stated:
(
Every system I know of that stores large numbers of big files stores them externally to the database. You store all of the queryable data for the file (title, artist, length, etc) in the database, along with a partial path to the file. When it's time to retrieve the file, you extract the file's path, prepend some file root (or URL) to it, and return that.
)
My questions are:
a)How do you store the partial path of the file?
b)How do you extract the file's path?
c)How do you prepend some file root and return it?
(Sorry I am very new and this bit I don't quite get. Any input or examples would be lovely.)
Btw, these are my codes for uploading the file, I just don't know the retrieve bit.
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'spellingbee');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$location = $dbLink->real_escape_string($_FILES['uploaded_file']['location']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `location`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$location}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
As far as I understand your problem you want to upload a audio file and save its name to database and then You want to retrieve it.
To do so just after your all validations (I am writing this code as if want to create a directory)
if(is_dir("audio")
{}
else
{mkdir("audio");}
$path = "http://www.domain.com/audio/".$_FILES['file']['name']; //prepend any path
// insert in database
move_uploaded_file($_FILES['file']['tmp_name'],$path);
And to retrive it:
just fetch the value of path from database.
Fetch From DB:
$q = mysql_query("select * from tablename");
while($r = mysql_fetch_array($q))
{
$path = $r['columnNameofPathinDatabase'];
echo $path;
}

add multiple pdf files to blobs usng php

I have to migrate a legacy database up to MySQL using PHP. One of the components of the old system is a large (>1000) list of attached files (mostly .pdf, some are .doc/.docx).
I have so far done the following:
created mysql table, with a blob to contain the file (this method has
been chosen for valid reasons)
imported all the data except the attachments
extracted all the attachments into a folder, naming each file with a unique name
added and populated in mysql a column containing the unique name of the attachment
created a file containing the full names of all the attachments in the folder.
To add a single file is the only solution that I found in stack
But my requirement is to RECURSIVELY go through the list of filenames and find the matching row in mysql, then insert the file from the folder into the blob
example ...
I have a text file with entries like this (filename, date created, size)..
024048DE44C-RUE_MA.pdf,05/24/2013,80233
024048DE44C-RUE.pdf,06/21/2013,85151
... (1000 more)
I have a file with name 024048DE44C-RUE_MA.pdf in the folder
I have a row column filename containing 024048DE44C-RUE_MA.pdf in mysql database
I think the solution is something like this, but need help in the middle bit.
$myfile = fopen("filelist.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$attfile =fgets($myfile);
...upload the file
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'dbase');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `deal_attachment` (
`deal_att_name`, `deal_att_mime`, `deal_att_size`, `deal_att_content`, `deal_att_created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
}
fclose($myfile);
Why don't you just use mysql LOAD_FILE function if you already have a table with the filename?
UPDATE mytable SET blobdata=LOAD_FILE(concat("/path/to/", filename));
Your files need to be on your mysql server in order for it to work.
If your only problem is how to read the CSV file you can do:
list($filename,$date, $size)=explode(",", $attfile);
Adam's suggestion worked perfectly for me with the important proviso in Windows that file path must contain double backslashes (so you would construct it like this
$path = 'c:\\dir\\subdir\\' . trim($filename) ;.
Following snippet of code shows the call ..
$query = "UPDATE `attachments` SET `att_content`=LOAD_FILE('" .$path . "') WHERE `att_name` = '" . $filename ."'" ;
$result = mysqli_query($dbcon,$query) ;
// Check if it was successful (maybe add some more insurance by going back to the database to see if the file is there - it can be that no error was reported but LOAD_FILE didn't work (like if the path is invalid)
if (false === $result) {
echo mysqli_error($dbcon);
die ;
} else { echo 'Success! Your file was successfully added!'; }

store image into mysql DB with php and display

Having big time problems in displaying an image out of my mysql database
I'm storing it in a longblob type
when the image is displayed i get a broken image icon
here is code for storing image
if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
//temporary file name
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$imageType = $_FILES['image']['type'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
VALUES
('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";
//For debugging purposes
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Your Image has been Added";
}
}
then printing the image
if(isset($_POST['usersImage'])){
//code to show images
$user = $_POST['usersImage'];
$sql = "SELECT * FROM `photos` WHERE userName = '$user'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
switch ($row['photoType']) {
case 'image/jpeg':
echo "<tr>";
echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";
echo "</tr>";
//echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
//echo '<p id="caption">'.$row['caption'].' </p>';
break;
}
}
}
as you can see my latest attempt was to use base64 encoding to print out the image
my previous try was the commented out code
When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.
<?php
$photo_bin = //binary data from query here;
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $photo_bin;
Quick example^ of a php script that can be requested by the browser from an img tag.
Validation is important. You are opening yourself up to so many security issues.
Never use $_POST / $_GET inside a sql statement. Escape them, better yet, use PDO statements. Validate that the image is actually an image, at this point, you could be entering any type of file into your table.
As you're finding, it's also far more difficult to store images in a database than on the filesystem. Usually, there are far more arguments to store the image on the filesystem than inside a table.
Having a quick look down your insertion code, I'm not quite sure why you're adding slashes to the binary data. remove the call to addslahes, and try that.

Categories