Search code examples
phpif-statementfile-get-contents

PHP file_get_contents and if returns false


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.
}

Solution

  • 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.)