I am using microsoft tag php library by Scott Vanderbeck.
It has a function to output the barcode to browser as an image to browser, but I would like download and save to disk. My goal is to loop through all the tags and download each barcode as an image onto a disk. I am not sure how to accomplish this.
Here is my code
require_once('MSTag_v2.php');
$MSTagAuthToken = "your token";
//Create an MSTag interface instance
$msTag = new MSTag();
//Create User Credentials
$userCredential = new UserCredential($MSTagAuthToken);
//Display Microsoft Tag image in browser
$result = $msTag->GetBarcode($userCredential,'MAIN','Cyclamen coum Pewter','jpeg',1);
if($result)
{
ob_start();
$length = strlen($result);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/jpeg');
print($result);
ob_end_flush();
exit;
}
else
{
echo $msTag->getLastException();
}
You could save the images directly to disk
if($result)
{
file_put_contents($filename, $result);
}
Just generate a filename for each so you do not overwrite them (maybe use tempnam()).
Related
I am getting response from cURL which is an encoded string format of pdf(i guess) - see attached image.
I am getting pdf file if i directly put the url in browser. Since its asking for api credentials for viewing the pdf, its not user friendly and i am looking for another way to directly download the file.
So i am trying to get the string content of the pdf file with cURL and i am getting exactly what in the image attached(only small portion attached).
Using that string content, i tried to save it as a plain txt file and from there i tried to decode the string text and to create a pdf file newly. After creating i need to download the same.
I could create text file with the string data i got from cURL and could create pdf also. But the downloaded file showing Failed to load PDF document.
Below is the code i have tried and i am not sure whether i tried correctly or not.
function pdf_download(){
$this->load->helper('file');
$curl = $this->api_call->callapi('GET',APIURL."carts/96171/tickets");
$content = $curl;
$my_file = FCPATH . '/document/text.txt';
if (write_file($my_file, $content) == FALSE)
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
$pdf_base64 = $my_file;
//Get File content from txt file
$pdf_base64_handler = fopen($pdf_base64,'r');
$pdf_content = fread ($pdf_base64_handler,filesize($pdf_base64));
fclose ($pdf_base64_handler);
//Decode pdf content
$pdf_decoded = base64_decode ($pdf_content);
//Write data back to pdf file
$pdf_file=FCPATH . '/document/ticket.pdf';
$pdf = fopen ($pdf_file,'w');
fwrite ($pdf,$pdf_decoded);//Creating a pdf from the encoded content in txt file
fclose ($pdf);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=tickets.pdf");
ob_clean(); flush();
readfile($pdf_file);//downloading the pdf file
exit();
}
Since streaming a download to the browser requires sending headers, you must not output anything before sending headers. Therefore, you must get rid of:
if (write_file($my_file, $content) == FALSE)
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
If you definitely need to check if the file was written (for debugging purposes, I assume) you may use CI's log_message() to write a debug entry in the logs or just set a control variable. For example:
if (write_file($my_file, $content) == FALSE)
{
log_message('debug', "Unable to write file");
$file_written = false;
}
else
{
log_message('debug', "File succesfully written");
$file_written = true;
}
Also, there's some headers missing to ensure the file is not streamed to the browser but sent for download, as well as some required to make sure the file is correctly downloaded
header('Content-Description: File Transfer');
header('Content-Type: '. mime_content_type($pdf_file)); // since you're using Codeigniter, this will try to use the correct mimetype
header('Content-Disposition: attachment; filename="ticket.pdf"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($pdf_file));
readfile($pdf_file);
The wrong line in the above given code is $pdf_decoded = base64_decode ($pdf_content);.
It should be changed to $pdf_decoded = $pdf_content;
Since string in encoded format is already getting which is needed for creating PDF. So no need to decode it.
Also the above code is reduced as below.
function pdf_download(){
$this->load->helper('file');
$this->load->helper('download');
$cart_id=$this->input->get('cart_id');
$curl = $this->api_call->callapi('GET',APIURL."cart/'.$cart_id.'/tickets");
$pdf_file=FCPATH . 'document\voucher-'.$cart_id.'.pdf';
if (write_file($pdf_file, $curl))
{
force_download($pdf_file, NULL);
}
}
I am trying to make a pdf-library where users can fill in which pdf-files they want to download and then the PHP file will get the filename from a database and make a path to the file and then it should download all selected files. But only get the last file downloaded.
This is my code for the download/output from the database:
Grateful for answer
$sql = "SELECT * FROM pdf WHERE id='$check'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$path = $row["path"];
$filename = $row["name"];
$file = $path."/".$filename;
header("Content-disposition: attachment; filename=".$filename);
header("Content-type: application/pdf");
readfile($file);
}
} else {
echo "0 results";
}
You can't send multiple files in a single response and you can't give multiple responses to a single request.
You might build an array of files to be downloaded and instruct the client (probably javascript in the browser) to request the files. Or you could zip them in a single ball and respond with that.
I am trying to download files from server and it works fine for pdf files, I am wondering is there a way to download any type of files such as doc, zip,.. etc.
My code:
<?php
$doc = $sqlite->readDoc($documentId);
if ($doc != null) {
header("Content-Type:" . $doc['mime_type']);
header('Content-disposition: attachment; filename="something"');
print $doc['doc'];
} else {
echo 'Error occured while downloading the file';
}
?>
You'll want to identify the file - maybe using this function:
http://php.net/manual/en/function.mime-content-type.php
and then you can create a switch to indicate the content-type and appropriate disposition. There's a decent example here: PHP - send file to user
A simple function that can be used to download any file formate form path.
function DownloadFile($strFilePath)
{
$strContents = file_get_contents(realpath($strFilePath));
if (strpos($strFilePath,"\\") > -1 )
$strFileName = substr($strFilePath,strrpos($strFilePath,"\\")+1);
else
$strFileName = substr($strFilePath,strrpos($strFilePath,"/")+1);
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"${strFileName}\"");
echo $strContents;
}
Usage Example
$file = $_GET['file_id'];
$path = "../uploads/".$file; // change the path to fit your websites document structure
DownloadFile($path);
I'm using code to print an image without showing the real path for it. But I have a problem when I want to save that image to my computer because its always show the PHP file name as the name for the image.
$id = intval($_REQUEST["id"]);
$getimage = $db->query("select id,img from bbup where id='$id'");
$fetch_image = $db->fetch($getimage);
$filename = $fetch_image['img'];
if (!$id) {
echo "Wrong Id";
exit;
}
if (!file_exists($filename)) {
echo "Image not found.";
exit;
}
$aaa = SITE_URL . $filename;
$imginfo = getimagesize($aaa);
header("Content-type: " . $imginfo['mime']);
readfile($aaa);
The php file is ppupload.php and when I want to save the image (let's say it is a PNG image) in the dialog box the name of the file show ( ppupload.php.png ) and I want it to be the image itself.
The image path stored into the database like this: folder/folder/filename.ext.
Have you tried setting the Content Disposition header?
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Type: application/octet-stream');
This might help.
You can try to add something like this header("Content-Disposition: inline; filename=\"myimg.png\"");
I currently have it working so it displays a dialogue box to save the image on your computer:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $jpg;
}
just wondered if there is any way to put the file straight into a directory/file without the need of a dialogue box?
like an uploader?
No, there is not.
Just Read the content of the page and save in a file using fopen , fwrite e.t.c.
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
ob_start();
header('Content-Type: image/jpeg');
echo $jpg;
$image=ob_get_clean();
//and here write it into file
}
OR following is my code you can remove unneccessary things that are not useful for you
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$im = $GLOBALS["HTTP_RAW_POST_DATA"];
$filename=$_GET['name'];
$fullFilePath='files/'.$filename;
$handle=fopen($fullFilePath,"w");
fwrite($handle,$im);
fclose($handle);
$returnVars = array();
$returnVars['write'] = "yes";
$returnString = http_build_query($returnVars);
//send variables back to Flash
echo $returnString;
}