News Tutorials Projects Reviews Authors Contact Search Links Admin
 

Reading File Directories : Useful Filters

So far we've produced useful scripts to view a list of files in a directory. However, this doesn't have much use yet.

Say you only want to see one sort of file from a directory. E.g. dated backup files, that have been saved to the server and you want to download.

Given that all files have the format #date#_backup.txt all we have to do is search for all files containing the word 'backup'.

Substr_count Filter

The function substr_count( string haystack, string needle) does a search for the first 'needle' in the 'haystack'. It returns the number of occurances. This can be used to see if one string occurs within another.
e.g.

<?php
if(substr_count("lepricorn.php", ".php")) {
	echo "php file";
} else {
	echo "not php";
}
?>

Of course, this script will always output php file, however it can easily be adapted to filter a list of files.

Hence:

<?php
$handler = opendir('.');
while($file = readdir($handler)) {
	if(substr_count($file, "backup")) {
		echo "$file<br>";
	}
}
closedir($handler);
?>

This will look at each file in the current directory (where the script is) do a substr_count looking for files with the string 'backup' in their name, and output a list of these files.

On the next page, you'll see my functions on reading a whole directory tree into an array.. and then outputting it to a page.

 


Author: Markavian
Last edited on: 22nd Jan, 9:14 am
Please rate this article.

« Prev page 'Read and Output' « » Next Page 'Repeating Functions' »

tutorial Pages