3

I wanted to try to convert an image to Binary.

I found a script online but it does not work.

Could someone please advise why?

<?php

$image="image003.jpg";

$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($fd, $size);
fclose ($fd);

$encoded= base64_encode($contents);

echo $encoded;

 ?>

I have an error come up on line 8 and 9

Warning: fread() expects parameter 1 to be resource

and

Warning: fclose() expects parameter 1 to be resource,
5
  • $fd isn't defined here. Please show the code where $fd is defined. Commented Feb 5, 2016 at 5:34
  • 1
    You should use $data instead of $fd Commented Feb 5, 2016 at 5:35
  • @RichardTheobald Thats the entire code. I found it online and thats the entire script included Commented Feb 5, 2016 at 5:35
  • I think you need to use $data and not $fd. Since you stored the file in $data Commented Feb 5, 2016 at 5:38
  • I have done the $data and it works perfect. Commented Feb 5, 2016 at 5:40

2 Answers 2

9

Use $data instead of $fd

$data = fopen ($image, 'rb');
$size=filesize ($image);
$contents= fread ($data, $size);
fclose ($data);
Sign up to request clarification or add additional context in comments.

Comments

2

As you can see here http://php.net/manual/en/function.fread.php.
So as you can read fread need a resource generate with fopen.

In your case:

<?php

$image = "image003.jpg"; // be careful that the path is correct

$data = fopen($image, 'rb');
$size = filesize($image);
$contents = fread($data, $size);
fclose($data);

$encoded = base64_encode($contents);

echo $encoded;

?>

2 Comments

This will not work for the same reason his original code doesn't work; $fd is undefined. ;-)
@RichardTheobald you right i missed the handler in fclose.. i was focus on fread, Thaks ;)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.