Hi all,

I m new to php and I have a simple problem. I want to check whether a file exists or not using php. I used the file_exists function for that but it doesn't work while I m able to open the same file using fopen..I know its a strange problem but I hope I get some inputs on this :o

Dani AI

Generated

As discovered, the problem turned out to be an incorrect path. asked about PHP version — a couple of version-sensitive details can affect how file_exists behaves, so a short checklist and a safe pattern follow.

Common causes when file_exists() returns false but fopen() appears to work:

  • Path confusion: relative paths are resolved against the current working directory, which may not be the script directory. Use absolute paths to avoid ambiguity.
  • URL vs filesystem: fopen() can open HTTP/FTP streams when wrappers are enabled, but file_exists() will not reliably confirm remote HTTP resources.
  • Stat cache: results are cached; use clearstatcache() before checking when files were just created/deleted.
  • Access restrictions: open_basedir or permission issues can prevent stat() from seeing a file.
  • Type checks: file_exists() returns true for both files and directories; use is_file() / is_dir() when appropriate.

Minimal troubleshooting and a robust pattern (print the resolved path, clear cache, test existence and readability):

$path = __DIR__ . '/data.txt'; // use dirname(__FILE__) on older PHP
clearstatcache();
var_dump($path, file_exists($path), is_file($path), is_readable($path));

Notes and cautions: avoid using realpath() to normalize a path before checking existence because it returns false for non-existent targets. Prefer building absolute paths (for example with __DIR__ or dirname(__FILE__)) and verify with var_dump() when results are unexpected. See the PHP manual for file_exists() for definitive behavior and edge cases: PHP manual: file_exists.

Recommended Answers

All 2 Replies

Member Avatar for Member #2466

What version of php are you using?

Hi TKS,

Thanks for responding.....But don't bother as the issue has been resolved now...It was a silly mistake on my part...:o..I got the file path wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.