read directory php

hi, i decided not too long ago to completly destroy my site and start from scratch. on the index page i want a news bar that will be updated automaticaly with the .txt files i put in the news/ directory.
the one i am using atm is this:

if ($handle = opendir(‘news/’)) {

$i = 1;
while ($file = readdir($handle)) {
	if($file != "." && $file != ".." && $file)

$n = 1;
while($n < $i) {
	$contents = file_get_contents("news/$n.txt");
	$contents2 = explode("|-|",$contents);
	echo "<div class=newstitle><a href='index.php?p=$n'>" . $contents2[0] . "</a></div><br/>";
	echo "<div class=newscont>" . $contents2[1] . "</div><br /><hr/>";



?> [/php]
and it works fine but i have to name the files 1.txt 2.txt 3.txt etc and would rather name them anything i wanted. so i started a new one and would work but when i open the link to index.php?p=$file it cannot read the txt file as it is trying to read (filename).txt.txt. please help


I am new to Php myself (still in the learning process)
However I was able to fix your issue.
To be honnest I have no clue if it’s secure in any way or if this is the right way to do it.
It works and thats fine for me.


<?php //Edited by Bullshizle $folder=dir("./news"); while($folderEntry=$folder->read()) { $folderEntry; $correctEntry = substr($folderEntry, 0,50); } if ($handle = opendir('news/')) { $i = 1; while($n < $i) { $contents = file_get_contents("news/$correctEntry"); $contents2 = explode("|-|",$contents); echo "
" . $contents2[0] . "

"; echo "
" . $contents2[1] . "

"; $n++; } closedir($handle); } ?>


I hope this was what you are looking for, I tested this script with random .txt file names in the correct “news” folder. :slight_smile:

here you go:

<?php //This is the directory route to the folder $Path = $_SERVER['DOCUMENT_ROOT'] . '/news'; $Linkdir=opendir($Path); // This is a relative link to the directory // if it is not in the same directory as the file you are displaying the news on $Linkdirectory = $_SERVER['DOCUMENT_ROOT'] . '/news'; $Linkpattern="\.(txt)$"; if(!$Linkdir) { die("Failed to read directory"); } $LinkS=readdir($Linkdir); $Linkcount="0"; while($LinkS) { if(ereg($Linkpattern, $LinkS)) { $Linkfeed[$Linkcount]=$LinkS; $Linkcount++; } $LinkS=readdir($Linkdir); } closedir($Linkdir); $Linklimit=count($Linkfeed); $Linklimit--; sort($Linkfeed); foreach($Linkfeed AS $Linkkey => $Linkvalue) { echo $Linkvalue; } break; ?>


the files must have a .txt extension. (anything else will be ignored)
the files must be in a directory called news.

thats is, no need to worry about naming etc, just put the file there and the script will find them and display the name for you, happy days :smiley:

Hope this is what you need,


Sponsor our Newsletter | Privacy Policy | Terms of Service