DirectoryIterator avoids manual opendir()/readdir() bookkeeping. The example below reads PHP files, extracts a literal HTML <title> when one is present, and uses filemtime() for the last-modified date.
<?php
$directory = __DIR__ . '/pages';
foreach (new DirectoryIterator($directory) as $file) {
if (!$file->isFile() || strtolower($file->getExtension()) !== 'php') {
continue;
}
$contents = file_get_contents($file->getPathname());
$title = '';
if ($contents !== false && preg_match('~<title>(.*?)</title>~is', $contents, $match)) {
$title = trim(strip_tags($match[1]));
}
echo htmlspecialchars($file->getFilename(), ENT_QUOTES, 'UTF-8') . ' | ';
echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . ' | ';
echo date('Y-m-d', $file->getMTime()) . '
';
}
?>
If page titles are generated dynamically at runtime, parsing the PHP source cannot reliably reproduce the rendered title. Use this technique only when the source contains a literal title.
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Displaying file name Title and date of last modification of all files of a directory</title>
</head>
<body>
<?Php
///////////////function my_strip///////////
function my_strip($start,$end,$total){
$total = stristr($total,$start);
$f2 = stristr($total,$end);
return substr($total,strlen($start),-strlen($f2));
}
/////////////////////End of function my_strip ///
///////////// Reading of file content////
$i=0; // Number of file counter
echo "<table><tr><th>URL ( Path + file name)</th><th>Title</th><th>Date</th></tr>";
$path="dir_name/path/";// Change this to your directory or path
$handle=opendir($path);
while (($file_name = readdir($handle))!==false) {
$str="";
if(stristr($file_name,".php")){ // We are checking for a perticular file extension, change this to match yours
$url="$path".$file_name;
$contents="";
$fd = fopen ($url, "r"); // opening the file in read mode
while($buffer = fread ($fd,1024)){
$contents .=$buffer;
}
/////// End of reading file content ////////
//////// We will start with collecting title part ///////
$title = my_strip("<title>","</title>",$contents);
$dt=date("Y-m-d",filemtime($url)); // Last modification date of the file
echo "<tr><td>$url</td><td>$title</td><td>$dt</td></tr>";
$i=$i+1;
}// end of if checking file extension
}// end of while reading directory
closedir($handle);
echo "</table>";
echo "Total Number of files checked = $i ";
?>
</body>
</html>
Here we have listed all details of a file but we can also store all these data in a table. Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.