0

I need to convert the image URL to base64_encode data using PHP. I am explaining my code below.

<?php
$path='https://www.jquery-az.com/html/images/banana.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64=base64_encode($data);
print_r($base64);exit;
?>

Here I am getting the blank output. Please help me to resolve this issue.

  • Enable the error logs. This path does not exist – pr1nc3 Nov 19 '18 at 12:46
  • I have changed the original path. In my case path is correct. –  Nov 19 '18 at 12:48
  • The above code returns the result in base64_encoding format. I don't get what's the error. Enable your error log. Blank page is never "blank" there are errors that are hidden there. – pr1nc3 Nov 19 '18 at 12:51
  • Duplicate of https://stackoverflow.com/questions/3967515/how-to-convert-an-image-to-base64-encoding – akshaypjoshi Nov 19 '18 at 14:12
  • Possible duplicate of [How to convert an image to base64 encoding?](https://stackoverflow.com/questions/3967515/how-to-convert-an-image-to-base64-encoding) – akshaypjoshi Nov 19 '18 at 14:12

4 Answers4

2

your code is working for me. I suppose the error is that in php.ini is disallowed to open remote urls: http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen set it to true

add this line and check for error message

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$path='https://www.jquery-az.com/html/images/banana.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64=base64_encode($data);
print_r($base64);exit;
myxaxa
  • 1,391
  • 1
  • 8
  • 7
1

Here's code to convert image to base64 format

        $path='http:\/\/abcd.com\/pub\/media\/catalog\/product\/\/m\/i\/mi-l32m5-ai.jpeg';
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        echo $base64;

Thanks

PHP Ninja
  • 1,055
  • 2
  • 9
  • 28
0

Try this code. It will help you.

According to his question, he needs to encode the image path. First, check if the image exists, if yes then encode its path .

$path = 'your-file-path';
$file = 'your-file';
$image_with_path = $path.'/'.$file;
if(file_exists($image_with_path)){
    $base64 = base64_encode($image_with_path );
}
Martin
  • 22,212
  • 11
  • 70
  • 132
Danish Ali
  • 2,354
  • 3
  • 15
  • 26
  • 1
    How will this code help? Please explain your answer – Martin Nov 19 '18 at 14:29
  • I would have thought that with 700+ Rep you would have understood the ability to **edit** your post and write a conherent and full answer in your post..... – Martin Nov 20 '18 at 10:55
0

Please use the unescaped url in $path variable,

<?php    
$path='http://abcd.com/pub/media/catalog/product//m/i/mi-l32m5-ai.jpeg';
Jeevan
  • 309
  • 1
  • 6