Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file_exists($var) not working

Tags:

php

file-io

I'm trying to write some code on my notebook and am using the xampp environment. I have the following piece of code:

class A {
...
  foreach ($blocks as $block) {
    $block = 'dir/dir2/' . $block;
  }
  if (file_exists($block) == true) {
    $var .= file_get_contents($block);
  }
}

When I echo the $block variable in the foreach loop, it gives back the path to the files. However, the file_exists function always returns false. Could you please help me figure out what's wrong here?

like image 361
Alex Avatar asked Sep 06 '25 10:09

Alex


2 Answers

file_exists purpose is to check if the supplied file exists. It's returning false. This means that the your file doesn't exist where php is looking. php might be looking in a different area than you expect. Looks like it's time for some debugging.

Run this to figure out where php is looking.

echo "current working directory is -> ". getcwd();

Is that where you want php to look? If not then change the directory php is looking in with the chdir function.

$searchdirectory = "c:\path\to\your\directory"; //use unix style paths if necessary
chdir($searchdirectory);

Then run your function (note: I flipped the slashes to backslashes in order to be consistent with windows style paths.)

class A {
...
  //change working directory
  $searchdirectory = "c:\path\to\your\directory"; //use unix style paths if necessary
  chdir($searchdirectory);

  foreach ($blocks as $block) {
    $block = 'dir\dir2\' . $block;

    if (file_exists($block) == true) {
      $var .= file_get_contents($block);
    }
  }
}
like image 68
jeremysawesome Avatar answered Sep 10 '25 04:09

jeremysawesome


Quoting someones comment on the php file_exists manual page,

Be aware: If you pass a relative path to file_exists, it will return false unless the path happens to be relative to the "current PHP dir" (see chdir() ).

In other words, if your path is relative to the current files directory, you should append dirname(__FILE__) to your relative paths, or as of PHP 5.3, you can just use __DIR__.

like image 33
tjm Avatar answered Sep 10 '25 06:09

tjm