hadi hadi - 5 months ago 47
PHP Question

file_get_contents giving error Filename cannot be empty

I have a PHP script that is throwing an error when execute it.


Warning: file_get_contents(): Filename cannot be empty in C:\Apache24\htdocs\image\test2.php on line 68`

Warning: exif_imagetype(): Filename cannot be empty in C:\Apache24\htdocs\image\test2.php on line 72`


Basically the script display images from rss feed, but the problem is not displaying all the images only some of them.

Here is the script

error_reporting(E_ALL);
ini_set("display_errors", 1);

$url = "http://www.sahafah.net/rss.php";

$rss = file_get_contents($url);

ini_set('mbstring.substitute_character', "none");
$rss1= mb_convert_encoding($rss, 'UTF-8', 'UTF-8');
$rss3 = simplexml_load_string($rss1);
if($rss3)
{
$items = $rss3->channel->item;
foreach($items as $item)
{
$title = $item->title;
$link = $item->link;
$published_on = $item->pubDate;
$description = $item->description;
$category = $item->category;
$guid = $item->guid;

$string2 = $item->description;
preg_match('/http.*.jpg/',$string2,$match2);
$convert = implode(",", $match2);

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($convert));

// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.exif_imagetype($convert).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="', $src, '">';
}
}

Answer

Like a lot of PHP questions the answer is there isnt actually anything wrong with your code. What you are seeing is not an error its a warning and these would be suppressed in production and your code will work just fine. Fixing warnings/notices is an issue of good practice and really down to you whether you bother. However if you want to get rid of them you can wrap any use of file_get_contents with:

if(file_exists($convert)){

    // Read image path, convert to base64 encoding
    $imageData = base64_encode(file_get_contents($convert));

    // Format the image SRC:  data:{mime};base64,{data};
    $src = 'data: '.exif_imagetype($convert).';base64,'.$imageData;

    // Echo out a sample image
    echo '<img src="', $src, '">';

}

Alternatively if you dont care about warnings and notices you can just do the following at the top of your code:

error_reporting(E_ERROR);

This will mean that the only stuff printed to screen will be actual errors and you wont have to be disturbed by warnings and notices.