1

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.

5
  • Enable the error logs. This path does not exist Commented Nov 19, 2018 at 12:46
  • I have changed the original path. In my case path is correct. Commented Nov 19, 2018 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. Commented Nov 19, 2018 at 12:51
  • Duplicate of stackoverflow.com/questions/3967515/… Commented Nov 19, 2018 at 14:12
  • Possible duplicate of How to convert an image to base64 encoding? Commented Nov 19, 2018 at 14:12

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

0

Please use the unescaped url in $path variable,

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

Comments

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

2 Comments

How will this code help? Please explain your answer
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.....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.