Link to home
Start Free TrialLog in
Avatar of usmbay
usmbayFlag for United States of America

asked on

display from directory

Hi,

I need to know how I can get last ten file in the directory using PHP ?? Thanks
Avatar of Neoific
Neoific

How do you want them to be sorted?
I've just written this for you, hopefully it will do the trick.  It's a function that returns the last 10 files modified in a given directory.  It has an optional parameter so you can specify how many files to return, if left blank, it defaults to 10.  The files are returned sorted in descending order.  You could list the files using a foreach loop.

E.G:

$files = list_files ("C:\\");
foreach ($files as $k => $v) {
    echo "$v<br />\n";
}

Hope this helps.

More Example Usage:

print_r ( list_files ("C:\\"));    //  Lists the last 10 modified files in the C:\ drive.
print_r ( list_files ("C:\\Program Files\\", 20));   // Lists the last 20 modified files in Program Files


<?php
	
	function list_files ($string_dir, $int_limit = 10) {
		$files = array();
		//	Get all the files in the directory, along with the last modified date.
		if ($dir_handle = opendir ($string_dir)) {
			while (false !== ($file = readdir ($dir_handle))) {
				$files[date("YmdHis", filemtime($string_dir . $file))] = $file;
	    	}
	    	krsort ($files);
	    	$files = array_chunk ($files, $int_limit, true);
	    	return $files[0];
		}
		return false;
	}
?>

Open in new window

Avatar of usmbay

ASKER

in this query the file_name represent the file name but the problem is the pdf_files includes all the files name either exist or not so when I excute the query it return all files name but  they're not physically exist
so I need to return file_name physically exist only in the directory

SELECT      file_name  FROM pdf_files;

file_name from the database
101
102
103
104
105

but what's in the directory is till 103 only so in the query return only up to 103.pdf  

Thanks
ASKER CERTIFIED SOLUTION
Avatar of morristhebear
morristhebear
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of usmbay

ASKER

ok it works but it return the files from last year it's log list , is there a way to return last 10 file only
Thanks