24

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

Jon Surrell
  • 9,444
  • 8
  • 48
  • 54
katie hudson
  • 2,765
  • 13
  • 50
  • 93

3 Answers3

51

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)));
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • Why is chunk_split() need here? – Trần Hữu Hiền Jul 20 '22 at 07:28
  • 1
    @TrầnHữuHiền From the php docs: ``chunk_split()`` can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts separator every length characters. Source: https://www.php.net/manual/en/function.chunk-split.php – Vincent V Aug 03 '22 at 10:27
6

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.

Ian
  • 24,116
  • 22
  • 58
  • 96
3

Convert base64 to pdf and save to server path.

// Real date format (xxx-xx-xx)
$toDay   = date("Y-m-d");

// we give the file a random name
$name    = "archive_".$toDay."_XXXXX_.pdf";

// a route is created, (it must already be created in its repository(pdf)).
$rute    = "pdf/".$name;

// decode base64
$pdf_b64 = base64_decode($base_64);

// you record the file in existing folder
if(file_put_contents($rute, $pdf_b64)){
    //just to force download by the browser
    header("Content-type: application/pdf");

    //print base64 decoded
    echo $pdf_b64;
}
sorak
  • 2,607
  • 2
  • 16
  • 24