3

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);

?>
2
  • Can you edit in the returned JSON string and the list of files in the folder to your question? Commented Sep 15, 2009 at 11:16
  • Did you check if glob returns the right value? Commented Sep 15, 2009 at 11:21

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it turned out that some of the filenames were capitalised.
2

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;
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.