2

I have a variable that comes from the "file_get_contents()" function. Using this variable with an if function always gives false.

$content = file_get_contents($url);
echo $content; // Echos 1
if ($content == "1") {
    // It doesn't matter if I use 1, '1' or "1"
    echo "True";
}
else {
    echo "False"; // Always echos this one.
}
Robin
  • 45
  • 7

2 Answers2

1

I think it could be better catch false in case failure (http://php.net/manual/en/function.file-get-contents.php)

$content = file_get_contents($url);
if ($content === false) {
    echo "False"; // or throw exception
}

echo "True";
Laky
  • 171
  • 1
  • 9
1

Your comparison fails because $content isn't what you think it is.

Most likely there are <html> tags or whitespace characters (like \n).

Make a hexdump of your content to see exactly what you are getting back from file_get_contents.

Hex dump function implemented in PHP.

Example:

$content = file_get_contents($url);

hex_dump($content);

Once you know what's inside $content you can filter it accordingly (strip_tags and trim were mentioned in the comments.)

Marco
  • 7,007
  • 2
  • 19
  • 49