Search code examples
phpfile-exists

file_exists always false


$var = "http://site.com/image.png";

if (file_exists($var))
    echo 'yes';
else
    echo 'no';

Why does this script always returns false?


Solution

  • Because that's not actually a file, rather it's a URL.

    Up until PHP5, the file_exists function was intended to detect whether a file or directory exists.

    At PHP5, support was introduced to allow support for some URL wrappers, as per the note on this page:

    Tip: As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.

    The wrappers are detailed here but, unfortunately, the http one does not support stat, a pre-requisite to allowing file_exists to work.

    If you're running on the server, you could possibly convert it using $_SERVER['DOCUMENT_ROOT'] or find another way to locate it on the file system.