PHP file_exists ($ var) not working

I am trying to write code on my laptop and am using the xampp environment. I have the following code:

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

When I repeat the $ block variable in the foreach loop, it returns the file path. However, the file_exists function always returns false. Could you help me figure out what is wrong here?

+3
source share
8 answers

file_existsThe goal is to check if the file exists. He returns a lie. This means your file does not exist where php is looking for. php may look in a different area than you expect. It seems like time for some debugging.

Run this to find out where php is located.

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

This is where do you want php to look? If not, then change the directory where php is looking for using the function chdir.

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

( : , Windows.)

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);
    }
  }
}
+8

php file_exists,

: to file_exists, false PHP- (. chdir()).

, , dirname(__FILE__) PHP 5.3, __DIR__.

+1

, , , 2 . , . , a.txt a, , a.txt, a.txt.txt. , → → →
. , file_exists().

+1

, .

:

echo getcwd();
$searchimg = getcwd().'\\public\\images\\pics\\'.$value['name'].'.'.$value['ext'];

, , :)

+1

, file_exists foreach. , $block .

EDIT: - .

0

file_exists() foreach?

class A {
  ...
  foreach ($blocks as $block) {
    $block = 'dir/dir2/' . $block;

    // Inside the loop      
    if (file_exists($block) == true) {
      $var .= file_get_contents($block);
    }
  }
}
0

, _ file_get_contents. :

  • file_exists: FALSE, - .
  • file_exists: UID/GID, .
  • file_get_contents: _exists ..

, !

0

If you use a variable for your file, make sure there is no space at the end. I went crazy until I found a solution: removing empty with trim (). See below.

if file_exists(trim($Filename))
-1
source

All Articles