0

I have this for loop in php:

for ($i=0; $i <= 10; $i++) {
      if (file_exists('./img/'.$i.'.jpg')) { 
          echo 'FILE: '.$i.'.jpg EXISTS!'; 
      } else { 
          echo 'FILE: '.$i.'.jpg NOT EXISTS!'; 
      }
}

I put in folder img only 1.jpg and 3.jpg so i need to get only for 1.jpg and 3.jpg file exists but i im getting for all files that does not exists or one file exists and all others does not exists...why is this function not returning correctly results?

Junius L
  • 15,881
  • 6
  • 52
  • 96
John
  • 1,521
  • 3
  • 15
  • 31

2 Answers2

1

Please try below code :

$dirname = "./img/";
$images = glob($dirname."*.jpg");

It will give you only existing .jpg file

or you can use your own code without else condition:

 for ($i=0; $i <= 10; $i++) {
            if (file_exists('./img/'.$i.'.jpg')){ 
            echo '<br/>FILE: '.$i.'.jpg EXISTS!'; 
           }
       } 
1

I think you are confused with the file structure and relative path

./ is same as / gets the same folders in script running dir, If you want to go to parent dir then you need to add ../

I have created the same program it works fine.

Running path /var/www/html/test and checking file folder /var/www/html/test/img and it works fine

   for ($i=1; $i <= 10; $i++) {
    $selva = "./img/$i.jpg";
      if (file_exists($selva)) {
          echo 'FILE: '.$selva.' EXISTS!<br>';
      } else {
          echo 'FILE: '.$selva.' NOT EXISTS!<br>';
      }
   }

I think you trying to access outside dir from the php running dir so you need to use ../

Else you can simply give the absolute path

you can get current folder by using dirname(__FILE__)

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71