For a controlled directory of HTML/PHP source files, loop through only expected extensions and extract the title defensively. Skip unreadable files instead of treating them as valid content.
$dir = __DIR__ . '/pages';
foreach (glob($dir . '/*.{html,htm,php}', GLOB_BRACE) ?: [] as $file) {
$text = file_get_contents($file);
if ($text !== false && preg_match('/<title>(.*?)<\/title>/is', $text, $m)) {
echo htmlspecialchars(basename($file) . ' : ' . trim($m[1])) . '<br>';
}
}This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
$path="../dir-name/";// Right your path of the directory
$handle=opendir($path);
while (($file_name = readdir($handle))!==false) {
We can open files of particular type by using its extensions. Here we will use one if condition to add or exclude different types of files. ( read more on stristr())
if(stristr($file_name,".php")){
// read the file now
}
Rest of the code is same as part 1 ( file search ). So here is the complete code.
<?
///////////////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;
$path="../dir-name/";// Right your path of the file
$handle=opendir($path);
while (($file_name = readdir($handle))!==false) {
if(stristr($file_name,".php")){
$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 ///////
$t=my_strip("<title>","</title>",$contents);
echo $t;
echo "<br>";
$i=$i+1;
}
}
echo $i;
?>
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.