Reputation: 1442
Have this function that encodes content of images file to base64.
function data_uri($file_to_get_contents, $mime) {
$contents = file_get_contents( '../images/'. $file_to_get_contents );
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
Actual location (url) of images file is this
$val_img = '../images/2014-12-03/13-1-b5780ffc85f5f29d5ce43d1f4e38003f.gif';
I need to access echo image using such url (without .gif
, .jpg
etc.).
$val_img = '../images/2014-12-03/13-1-b5780ffc85f5f29d5ce43d1f4e38003f';
Decided to use glob
. And use code below.
$val_img = glob($val_img. '×.*');
Tried also
$val_img = glob( '×'. $val_img. '*' );
With this see empty array
echo '<pre>', print_r($val_img, true), '</pre> $val_img <br/>';
And with this
echo '<img src='. data_uri($val_img , "../images"). ' alt="Image" >';
See error like Warning: file_get_contents(../images/Array) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: No such file or directory
Error informs that in this $contents = file_get_contents( '../images/'. $file_to_get_contents );
line is error.
But seems something incorrect with this $val_img = glob($val_img. '×.*');
What would be correct code?
Here is my code that works
function data_uri($file_to_get_contents, $mime) {
$contents = file_get_contents( '../images/'. $file_to_get_contents );
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
$val_img = '../images/2014-12-03/13-1-b5780ffc85f5f29d5ce43d1f4e38003f';
$val_img = glob( $val_img. '*' );
echo '<img src='. data_uri($val_img[0] , "../images"). ' alt="Image" >';
Upvotes: 0
Views: 94
Reputation: 44851
The problem is that you are passing an array to your function data_uri
.
glob
returns an array. That means that $val_img
is an array, not a string. But you are treating it as a string when you pass it to data_uri
as the parameter $file_to_get_contents
. Specifically, you use it as a string in this line:
$contents = file_get_contents( '../images/'. $file_to_get_contents );
Easiest way to fix this: change your call to data_uri
, like so:
echo '<img src='. data_uri($val_img[0] , "../images"). ' alt="Image" >';
Another option is to loop over the array, like this:
foreach($val_img as $one_img) {
echo '<img src='. data_uri($one_img , "../images"). ' alt="Image" >';
}
Edit: You also have a logic error in your code. There's no need for the ×
character (whatever that is); your file names don't contain one. Just do $val_img = glob($val_img. '.*');
Side note: I have found that the best way to prevent these kinds of errors is to use a good IDE (I personally prefer PHPStorm) and add PHPDoc blocks to all your functions describing the parameter types. Then, if you try to pass an array when your function expects a string, you will get a warning from the IDE. Catching stuff like this at development time makes for much cleaner code and helps you avoid releasing errors into the wild.
Upvotes: 3