Search code examples
phpfile-get-contentsfile-put-contents

Directly save image generated with php


Im generating Identicons using a php script. Showing the result using a <img> works fine

$input="create_image/identicon.php?size=48&hash=$hashvalue";
$output=$username."_userimage.png";

This works:

echo "<img src='$input'>";

But this doesn't: (It just creates an empty file)

file_put_contents($output, file_get_contents($input));

and throws a no such file or directory exception, tho its the same url as the one used for the src property showing the image.

What is the problem trying to save it like that?

Im not sure whether the problem is the file_put_contents or the file_get_contents


Solution

  • You can use file_get_contents() to load a file from the filesystem or from a remote host over HTTP. But you need to give PHP the full url in order to make use of the HTTP functionality (the php.ini also needs to allow this). Otherwise it literally searchs for the file create_image/identicon.php?size=48&hash=$hashvalue (variables of course replaced) on the filesystem.