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

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

Why does this script always returns false?

1
  • 1
    Because you're looking at a URL, not a physical path on your computer (or web server) Commented Feb 3, 2011 at 8:14

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to check the presence of remote files (actually "resources") then use:

$i = get_headers($url);
$ok = strpos($i[0], "200");

And check the HTTP status code.

Comments

0

Then most probably your server does not allow outside connections from within PHP.

You can check this by opening a local file and see if that works. If it does, your code is correct.

Make sure allow_url_fopen is set to ON.

1 Comment

Never mind, I jumped to conclusions. @paxdiablo has the correct answer.
0

The $var variable should describe a path on the system, not a URL. For example

$var = "/var/www/html/image.png";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.