简体   繁体   中英

PHP - Display Content in Json with Specific File Extension & Huge Records

As a PHP developer i am stuck. My mobile app developer needs an API where my PHP code will return only imagenames from a folder with following twist

1) There are almost 15,000 images in wp-content/uploads/2015/04 folder, which times out the page.

What i have tried is following code which works great, if there are less number of images in that folder.What should i do in this case.

<?php

$dir          = "wp-content/uploads/2015/04";
$return_array = array();

if(is_dir($dir)){

    if($dh = opendir($dir)){
        while(($file = readdir($dh)) != false){

            if($file == "." or $file == ".."){

            } else {
                $return_array[] = $file; // Add the file to the array
            }
        }
    }

    echo json_encode($return_array);
}

?>

I would recommend setting the php time limit to be higher using set_time_limit().

Also, try caching the results in a database or file, so you don't have to do an expensive lookup every time.

An alternative to opendir which might be faster would be to use the shell's "ls" command (note that this would be OS-specific, so reduce code portability).

For example:

echo json_encode(explode("\n", trim(`ls -1 wp-content/uploads/2015/04`)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM