2

i'm trying to make a php script to get a user picture but when i the returned image is empty, it should return the standard image. This is the code i have that does not work...

<?php
if (isset($_GET['user']))
{
$user = $_GET['user'];
$skinURL = "http://s3.amazonaws.com/MinecraftSkins/".$user.".png";
} 
$debugImage = imagecreatefrompng("http://s3.amazonaws.com/MinecraftSkins/".$user.".png");
if (empty($debugImage)) // here it checks if $debugImage is empty (doesn't work)
{
    $skinURL = 'http://www.minecraft.net/images/char.png';
}
$skin = imagecreatefrompng($skinURL);
?>

any ideas?

edit 1: The link returns a image if it exists, and nothing if it doesn't exist. Thanks already for the answers!

Robbe7730
  • 21
  • 1
  • 5

2 Answers2

6

There's no such thing as "empty image". Even if it's a blank image there are still pixels with the same color, which would be hard to classify as "empty". Instead why not checking if the file exists?

function c_file_exists($file){
    $file_headers = @get_headers($file);
    if(strpos($file_headers[0], '404 Not Found')) {
        return false;
    }
    return true;
}
if (!c_file_exists("http://s3.amazonaws.com/MinecraftSkins/".$user.".png"))
{
    $skinURL = 'http://www.minecraft.net/images/char.png';
}

Source: http://www.php.net/manual/en/function.file-exists.php#75064

EDIT

I edited the condition of the function to work with different versions of HTTP as 2 is out now and someone may still be using 1.0

Community
  • 1
  • 1
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • Well it's actually just no image at all when the user doesn't exist, but still thanks for the reply! (sorry for me being so late in my comments) – Robbe7730 Dec 22 '13 at 08:31
0

Two things to note here:

First, ensure allow_url_fopen is enabled in your environmental settings

Secondly, add a check to ensure that the remote file exists. You could make a curl request to do this. Or use the method php_nub_qq mentions in his answer.

Better yet, copy the remote image to your server before calling imagecreatefrompng. Take a look at this thread

Community
  • 1
  • 1
dnshio
  • 914
  • 1
  • 8
  • 21