tags:

views:

268

answers:

2

I don't know any PHP so another developer helped me out with this code. I am trying to return the names of all the files in a folder on my server. These are then passed to my iPhone app which uses the data. However, I have 160 files in the folder and the JSON string only returns 85. Is there something wrong with this code:

 <?php
$path = 'Accepted/';

# find all files with extension jpg, jpeg, png 
# note: will not descend into sub directorates
$files = glob("{$path}/{*.jpg,*.jpeg,*.png}", GLOB_BRACE);

// output to json
echo json_encode($files);

?>
+1  A: 

There is no reason this code should fail. However, your $path variable should not end in a slash (as you have that in the glob call).

Things to look at:

  • Are you certain that all the files are .jpg, .jpeg or .png files?
  • Are you certain that some of the files are not .JPG, .JPEG or .PNG (case matters on Unix/Linux)
  • Try print_r on the $files variable. It should list all the matched files. See if you can identify the files that aren't listed.
Vegard Larsen
Thanks, it turned out that some of the filenames were capitalised.
Gary
+1  A: 

If this is on a UNIX-like system, your files are case-sensitive. It might be that *.jpg will match, whereas *.JPG or *.jpG won't.

The following function goes through all files in $path, and returns only those which match your criteria (case-insensitive):

<?php
$path = 'Accepted/';
$matching_files = get_files($path);
echo json_encode($matching_files);

function get_files($path) {
    $out = Array();
    $files = scandir($path); // get a list of all files in the directory
    foreach($files as $file) {
         if (preg_match('/\.(jpg|jpeg|png)$/i',$file)) {
             // $file ends with .jpg or .jpeg or .png, case insensitive
             $out[] = $path . $file;
         }
    }
    return $out;
}
?>
Piskvor