开发者

Display the first 5 file names using opendir() and $file using PHP

$d = opendir("docs");

while (($file = readdir($d)) !== false) 开发者_运维技巧{ 

    if (($file != ".") && ($file != "..")){
        }
}

I want to be able to display the first 5 file names.

Here is the twist, I have a next button, which I want to display the next 5 filenames

Thanks Jean


You could use a counter variable, and make sure it doesn't go to more that 5 ?

A bit like that :

$counter = 0;
$d = opendir("docs");
while (($file = readdir($d)) !== false && $counter < 5) { 
    if (($file != ".") && ($file != "..")){
        // ...
        $counter++;
    }
}


Not tested : maybe you'll have to use <= instead of <


you can glob all the files into an array first. then use a loop to go over the array, in steps of 5.

$filenames = array_filter(glob($path.'*'), 'is_file'); 


You can make use of a counter as follows:

$d = opendir("docs");
// check for opendir error here.

$count = 0; // initialize counter.

while (($file = readdir($d)) !== false) { 

    if (($file != ".") && ($file != "..")){
        //....process files here.

        $count++; // done with one file..increment counter.
        if($count == 5) // have we reached the limit ?
            break; // if yes break.


    }
}


@Edited Question

I suggest the next button submits a form or somehow creates a new request? So just pass the current counter value.

$counterLimit = 5;
$counterStart = $_POST['counterStart']; //Pass the start value
$counterEnd= ($counterLimit + $counterStart);
$dir = opendir("dir");
$i = 0;
while (($file = readdir($dir) !== false) && ($i <= $counterEnd)) {
   if ($i >= $counterStart) {
       //Do something
   }
   $i++;
}

Not tested. But something like that.


$from = GET["from"];

$counter = 0;
$fileCounter = 0;
$d = opendir("docs");
while (($file = readdir($d)) !== false && $counter < 5) { 
    if (($file != ".") && ($file != "..") && $from == $fileCounter){
        // ...
        $counter++;
    } else {
        $fileCounter++;
    }
}

The code above isn't testet but it should work something like that.

On the next button you now have something like files.php?from=5 to get the files from 5-10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜