user1320260
user1320260

Reputation:

php - file_get_contents() is empty but content is present

I generate an image based in data uri within a simple php script. The path to the file works fine when used inside an image tag. I am trying to download this image using php zip. It is currently failing due to content is empty.

Works fine:

$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
echo file_get_contents( $image2 ); // returns content to screen

Fails:

$image2 = "/myPath/myPath1/script.php";
echo file_get_contents( $image2 ); // nothing displayed

If I put this path inside an image tag on the screen it's fine

<img src="/myPath/myPath1/script.php" />

script.php Script used to generate image

$imgstr = "data:image/jpeg;base64,/9j/........... rest of string";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}

// Decode the data
$content = base64_decode($matches[2]);

// Output the correct HTTP headers
header('Content-Type: '.$matches[1]);
//header("Content-Type: image/jpeg"); // tried this made no difference

// Output the actual image data
echo $content;

I have tried everything and seem to be going around in circles. Any advice is very much welcomed.

Upvotes: 0

Views: 1306

Answers (1)

Uri Goren
Uri Goren

Reputation: 13700

The

<img src="/myPath/myPath1/script.php" />

HTML tag, causes the execution of the file that corresponds to the /myPath/myPath1/script.php querystring.

The file can be located any where on the server, depending on your apache/nginx and .htaccess configuration.

On the other hand,

$image2 = "/myPath/myPath1/script.php";
echo file_get_contents( $image2 )

Tries to read to the contents of the file located on that specific path

If you want to execute that file, and you know the path to it:

$image2 = "/myPath/myPath1/script.php";
ob_start();
include $image2;
$contents=ob_get_clean();

Upvotes: 1

Related Questions