How to get title from html file using directory - php - php

Fairly new to php, so bear with me. I'm trying to figure out how to read a directory/folder and return both the filename/path and the title of that file into a li.
$handle = opendir('.');
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($filename, '.'), 1));
if($extension == 'html' || $extension == 'htm' || $extension == 'php'){
echo "<a href='".$filename."'><li class='"iso_block"'><span>"**Title Tag Here**"</span></li></a>";
}
}
^code from miro(cheers/thanks)
js.Fiddle link for visual: http://jsfiddle.net/AagGZ/547/

$handle = opendir('.');
$dom = new DOMDocument();
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
$title = 'Untitled Document';
if($dom->loadHTMLFile($urlpage)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
echo "<a href='$filename'><li class='iso_block'><span>$title</span></li></a>";
}
}

Related

echo all pages with each pages unique title from directory/folder

I have a folder in the main root, News. In that folder, I have 10 pages, each one has a unique page title:
/news/Today-is-cold-outside.php title = Today is Cold
/news/Watch-out-for-the-smelly-frogs.php title = Smelly Toads
I can get the code below to work so that it will fetch each page and provide a link to each page with the page name $file, example: Today-is-cold-outside.php, not $title = Today is Cold.
How can I get the page to display the specific Page Title for each link $title?
I know I have $file listed below instead of $title in the link, I left it in there so you can see where I am wanting to display the title and that if you test it, it will show you that it is getting the $file=pages from the directory/folder news.
Thanks in advance, I have been working for 2 days on this and cant find a solution.
<?php
$handle = opendir('news');
$dom = new DOMDocument();
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
if($dom->loadHTMLFile($urlpage)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
echo "<a href='news/$file'>$file</a>";
}
}
?>
Try nodeValue
$title = $list->item(0)->nodeValue
change
$dom->loadHTMLFile($file)
and
echo "<a href='blog/$file'>$title</a>";
If $file = Today-is-cold-outside.php
And you want $title to = Today is Cold
Do this:
$title = $file;
$title = str_replace('-',' ',$title);
$title = str_replace('.php','',$title);
echo $title;
This will convert dashes to spaces, and remove the .php extension.
If you like my answer I can also convert each word from lowercase into uppercase as well as limit the max number of words to 3 if you want.
Try this out:
<?php
$handle = opendir('news');
$dom = new DOMDocument();
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
if($dom->loadHTMLFile($urlpage)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
$title = $file;
$title = str_replace('-',' ',$title);
$title = str_replace('.php','',$title);
echo '<a href="blog/'.$file.'">';
echo $title;
echo '</a>';
}
}
?>
<?php
$handle = opendir('blog');
$dom = new DOMDocument();
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
if($dom->loadHTMLFile('blog/'.$file)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
echo "<a href='blog/$file'>$title</a><br/>";
}
}
?>
<?php
$title = $file;
$title = str_replace('-',' ',$title);
$title = str_replace('.php','',$title);
echo '<a href="blog/'.$file.'">';
echo $title;
echo '</a>'; ?>
<?php
$handle = opendir('news');
$dom = new DOMDocument();
$title = '';
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
if($dom->loadHTMLFile('news/'.$file)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
echo "<a href='news/$file'>$file</a>";
echo $title;
}
}
?>
my directory name is "news"
<?php
$handle = opendir('news');
$dom = new DOMDocument();
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if ($extension == 'html' || $extension == 'htm' || $extension == 'php') {
if($dom->loadHTMLFile('news/'.$file)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
echo "<a href='news/$file'>$title</a><br/>";
}
}
?>

Only show pictures

I have this script:
$uploadsDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .'/slides/head/';
if ($handle = opendir($uploadsDirectory)) {
$uplo = array();
while (false !== ($file = readdir($handle))) {
array_push($uplo, $file);}
sort($uplo,SORT_NATURAL | SORT_FLAG_CASE);
$user = array();
foreach($uplo as $fname) {
if($fname != ".." && $fname != "."){
if(substr($fname,0,1) != "_")
echo "<div class='bgitem' id='head'>$fname</div>";
else
array_push($user, "$fname");}}
closedir($handle);}
It works fine, but how can I make it so it only shows the pictures? (I have other files that aren't photos, so it displays a broken picture instead.)
A simple way would be to have it test whether the file is an image in the same line where you test if the file is a parent directory or the current directory (if($fname != ".." && $fname != "."){)
You can use getimagesize() to determine if the file is any kind of image. If it is not an image, it will return zero.
$uploadsDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .'/slides/head/';
if ($handle = opendir($uploadsDirectory)) {
$uplo = array();
while (false !== ($file = readdir($handle))) {
array_push($uplo, $file);}
sort($uplo,SORT_NATURAL | SORT_FLAG_CASE);
$user = array();
foreach($uplo as $fname) {
if($fname != ".." && $fname != "." && getimagesize($fname) != 0){ //Tests if file is an iamge
if(substr($fname,0,1) != "_")
echo "<div class='bgitem' id='head'>$fname</div>";
else
array_push($user, "$fname");}}
closedir($handle);}
Solution for you:
$extension = explode(".", $fname);
$extension = (isset($extension) && count($extension) > 0)?strtolower($extension[count($extension) -1]):null;
if(in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])){
//Show the image
}else{
//dont show image
}

opendir array exclude file from results

The code below will select all of my php files from the named folder and then shuffle them and echo 10 results on my page, the folder contains an index.php file which i would like to be excluded from the results.
<?php
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
<?=$thelist?>
I have found a code to exclude index.php but I'm not sure how to incorporate it into my code above.
<?php
$random = array_values( preg_grep( '/^((?!index.php).)*$/', glob("../folder/*.php") ) );
$answer = $random[mt_rand(0, count($random) -1)];
include ($answer);
?>
Why not just modify the line
if ($file != "." && $file != "..") {
to
if ($file != "." && $file != ".." && $file != 'index.php') {
An approach based on glob() instead of readdir():
<?php
$files = glob('../folder/*.php');
shuffle($files);
$selection = array_slice($files, 0, 11);
foreach ($selection as $file) {
$file = basename($file);
if ($file == 'index.php') continue;
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
// ...
}
You can use
$it = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
$it = new RegexIterator($it, '/.php$/i', RegexIterator::MATCH);
$exclude = array("index.php");
foreach ( $it as $splFileInfo ) {
if (in_array($splFileInfo->getBasename(), $exclude))
continue;
// Do other stuff
}
Or Simply
$files = array_filter(glob(__DIR__ . "/*.php"), function ($v) {
return false === strpos($v, 'index.php');
});
You can exclude it while you reading directory content (like you do with '.' and '..'):
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != "index.php") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != 'index.php')
$fileTab[] = $file;
}
you could just change this line if ($file != "." && $file != "..") { to if ($file != "." && $file != ".." && $file != 'index.php') {
The code you found replaces your cumbersome directory reading loop.
And it should be just:
$files = preg_grep('~/index\.php$~', glob("../folder/*.php"), PREG_GREP_INVERT);
Get 10 elements as before:
$files = array_slice($files, 0, 10);
Then output those.

How to exclude certain file types with PHP readdir?

I am using a php scan directory script that will scan the contents of a directory and then populate the page with links to the directory contents.
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?
I am wondering how I can exclude certain files or file types like test.xml, durka.xslt or .html from showing up on the populated page. I have some code but not sure how to integrate it. Any help would be very appreciated...
?php
if ($handle = opendir(‘.’)) {
while (false !== ($file = readdir($handle)))
{
if ($file != “.” && $file != “..”
&& $file != “NOT-TO-BE-IN-1.php”
&& $file != “NOT-TO-BE-IN-2.html”
&& $file != “NOT-TO-BE-IN-3.jpg”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
&& $file != “”
)
<?php
// These files will be ignored
$excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
);
// These file extensions will be ignored
$excludedExtensions = array (
'html',
'htm',
'php'
);
// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Loop through directory
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
$extn = explode('.',$file);
$extn = array_pop($extn);
// Only echo links for files that don't match our rules
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)) {
$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."
&& $file != "NOT-TO-BE-IN-1.php"
&& $file != "NOT-TO-BE-IN-2.html"
&& $file != "NOT-TO-BE-IN-3.jpg"
&& substr($file,-strlen(".html")) != ".html" //if you don't want to include .html files, for instance
&& substr($file,-strlen(".js")) != ".js" //if you don't want to include .js files, for instance
&& $file != ""
) {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
Other way:
$excludeExtensions = array(
'php',
'html',
'jpg'
);
if ($file != "." && $file != ".." && !in_array(pathinfo($file, PATHINFO_EXTENSION), $excludeExtensions))
EDIT: again I was too late:)
you can also just use glob:
foreach (glob("*.{php|html|jpg}",GLOB_BRACE) as $file) {
echo file_get_contents($file);
}
see http://php.net/manual/en/function.glob.php for more info
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".."
&& $file != "NOT-TO-BE-IN-1.php"
&& $file != "NOT-TO-BE-IN-2.html"
&& $file != "NOT-TO-BE-IN-3.jpg"
&& $file != ""
&& $file != ""
&& $file != ""
&& $file != ""
&& $file != ""
)
echo file_get_contents($file);
will show contents of all pages which haven't name
NOT-TO-BE-IN-1.php
NOT-TO-BE-IN-2.html
NOT-TO-BE-IN-3.jpg
you can restrict certain filepath with
if (!preg_match('/(php|html|jpg)/', $file))
Try something like:
$excluded_files = array('test.xslt');
$excluded_ext = array('html');
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." &&
!in_array($file, $excluded_files) &&
!in_array(pathinfo($file, PATHINFO_EXTENSION), $excluded_ext))
{
// do stuff
}
}

Getting last modified info from files with PHP when filemtime, stat['mtime'], and get_headers fail

I'm trying to display images in the reverse order of when they were last modified. Unfortunately, get_headers() seems to only work for urls, and both stat['mtime'] and filemtime() fail for me. Are there any other ways for me to get the last modified info for a file? Here's my code at the moment:
if (isset($_GET['start']) && "true" === $_GET['start'])
{
$images = array();
if ($dir = dir('images'))
{
$count = 0;
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
$lastModified = filemtime($file);
$images[$lastModified] = $file;
++$count;
}
}
echo json_encode($images);
}
else { echo "Could not open directory"; }
}
You should prepend the path to the filename, before calling filemtime($file). Try
$lastMod = filemtime("images/".$file);

Categories