Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP base64 encode a pdf file

Tags:

php

base64

I am using an API where I can send a document to something like dropbox. According to the documentation, the file which is sent needs to be BASE64 encoded data.

As such, I am trying something like this

$b64Doc = chunk_split(base64_encode($this->pdfdoc));

Where $this->pdfdoc is the path to my PDF document.

At the moment, the file is being sent over but it seems invalid (displays nothing).

Am I correctly converting my PDF to BASE64 encoded data?

Thanks

like image 379
katie hudson Avatar asked Dec 09 '15 15:12

katie hudson


People also ask

How can I encode a PDF to base64 in PHP?

This can be done with the help of file_get_contents() function of PHP. Then pass this raw data to base64_encode() function to encode. Required Function: base64_encode() Function The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64.

What is base64 encoding in PHP?

Description ¶ base64_encode(string $string ): string. Encodes the given string with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies. Base64-encoded data takes about 33% more space than the original data.

What is base64 decode in PHP?

The base64_decode() is an inbuilt function in PHP which is used to Decodes data which is encoded in MIME base64. Syntax: string base64_decode( $data, $strict ) Parameters: This function accepts two parameter as mentioned above and described below: $data: It is mandatory parameter which contains the encoded string.


2 Answers

base64_encode takes a string input. So all you're doing is encoding the path. You should grab the contents of the file

$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));
like image 131
Machavity Avatar answered Sep 19 '22 15:09

Machavity


base64_encode() will encode whatever string you pass to it. If the value you pass is the file name, all you are going to get is an encoded filename, not the contents of the file.

You'll probably want to do file_get_contents($this->pdfdoc) or something first.

like image 23
Ian Avatar answered Sep 23 '22 15:09

Ian