PHP get pdf file from base64 encoded data string - php

I have a base64-encoded string containing a pdf. How to create a .pdf file from this encoded string using php?
Something like Content-type:application/pdf in header function?
this is the base64 encoded string

Try this piece of code
$pdf_base64 = "base64pdf.txt";
//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 = fopen ('test.pdf','w');
fwrite ($pdf,$pdf_decoded);
//close output file
fclose ($pdf);
echo 'Done';

With this you can create and open the file... but maybe this is not the answer to the question
$data = base64_decode($this->Get(self::Body));
file_put_contents('file.pdf',$data);
The answer is echo the content with a header :
$data = base64_decode($this->Get(self::Body));
header('Content-Type: application/pdf');
echo $data;

Related

How to create a pdf file from encoded string content - Codeigniter

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

Return name of created file from decoded string in php

Hi i have the following code to decode and save image
$photo = $_REQUEST['image'];
$binary = base64_decode ($photo);
header ('Content-Type: bitmap; charset=utf-8');
$file = fopen ('uploads/'.time().'.png', 'wb');
fwrite($file, $binary);
fclose ($file);
This works fine but i will like to get the name of the image after it is written and store that name as a variable to use in the rest of the code where it will be saved in mysql database. I can write to mysql i just need to get the file name. Thanks
You are already naming the file yourself. Just store it in a variable before you write the file.
$filename = time().'.png';
$file = fopen ('uploads/'.$filename, 'wb');

How to convert Excel file to text file in php?

I want to convert an excel file to a text file. I have tried this code but it doesn't work:
$destination = 'products.xls';
$section = file_get_contents($destination);
$File = "file.txt";
$File = str_replace(';','#',$File);
$Handle = fopen($File, 'w');
$Data = $section;
fwrite($Handle, $Data);
print "Data Written"; die;
When I open the text file it shows me special characters and when I convert csv to text it shows me the right result. Please provide any helpful links.
You cannot read the Excel file that way. Excel file is binary file that follows the XLS format while file_get_contents is for pure text file. You need a library (like https://github.com/PHPOffice/PHPExcel) to read the content then write to text.

how to save the image with name posted in the request

I have this simple php file that read the image from my android application:
<?php
$base=$_REQUEST['image'];
$cod=$_REQUEST['cod_anagrafico'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
//binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
print($binary);
$theFile = base64_decode($image_data);
$file = fopen('docs/test2.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=docs/test.jpg>';
?>
But it save my pic with the standard name "test". So i need to save this image with the name of variable "cod". How can i do that? And how can i delete the image when the process end?
Thanks
Change this line and you should be ok
$file = fopen("docs/{$cod}", 'wb');

PHP View Picture From Base64 String

I am connecting to Active-Directory and getting the thumbnailPhoto attribute successfully.
I have stored the file in the DB using Base64 encoding which makes the result look like:
/9j/4AAQSkZJRgABAQEAYABgAAD/4RHoRXhpZgAATU0AKgAAAAgABQEyAAIAAAAUAA ...
(Full Base64 encoded string: http://pastebin.com/zn2wDEmd)
Using a simple Base64 Decoder and decoding the string into a binary file and rename that to jpeg and open with an image viewer (here: Irfan View) I get the correct picture - see yourself:
How do I achieve this through PHP - I have tried using:
<?php
$data = '/9j/4A...'; //The entire base64 string - gives an error in dreamweaver
$data = base64_decode($data);
$fileTmp = imagecreatefromstring($data);
$newImage = imagecreatefromjpeg($fileTmp);
if (!$newImage) {
echo("<img src=".$newImage."/>");
}
?>
I'm just getting a blank page!
Your problem is that imagecreatefromstring() doesn't return a file, but rather an image in memory that should be output with the correct headers.
$data = base64_decode($data);
// Create image resource from your data string
$imgdata = imagecreatefromstring($data);
if ($imgdata) {
// Send JPEG headers
header("Content-type: image/jpeg");
// Output the image data
imagejpeg($imgdata);
// Clean up the resource
imagedestroy($imgdata);
exit();
}

Categories