Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON Return String question

Tags:

json

php

iphone

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 Answers

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.
like image 200
Vegard Larsen Avatar answered Nov 27 '25 14:11

Vegard Larsen


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;
}
?>
like image 20
Piskvor left the building Avatar answered Nov 27 '25 16:11

Piskvor left the building



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!