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

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/>";
}
}
?>

Related

Insert Images from folder and subfolder php

Im trying to insert into html all images that are on the folder "assets/imagens/" and on any subfolders. I also need help to validate not to echo the subfolders.
Im using the code below:
$path = "assets/imagens/";
$diretorio = dir($path);
while($arquivo = $diretorio -> read()){
if($arquivo != '.' && $arquivo != '..'){
echo '<div href="#" class="list-group-item">';
echo '<span class="close-button" secao="imagens">x</span>';
echo "<img class='max-width' src='".base_url().$path.$arquivo."' />";
echo '</div>';
}
}
$diretorio -> close();
$path = "assets/imagens/";
echo_directory_images($path);
function echo_directory_images($path)
{
$diretorio = dir($path);
while($arquivo = $diretorio -> read()){
if($arquivo != '.' && $arquivo != '..'){
if( is_dir($path.$arquivo))
{
//if subfolder
echo_directory_images($path.$arquivo.'/')
}
else{
echo '<div href="#" class="list-group-item">';
echo '<span class="close-button" secao="imagens">x</span>';
echo "<img class='max-width' src='".base_url().$path.$arquivo."' />";
echo '</div>';
}
}
}
}
You may want to give a try to this function. I doubt if this will work exactly but this will surely give an idea about how to recursively call folders and subfolders.
Try this :
function listDir( $path ) {
global $startDir;
$handle = opendir( $path );
while (false !== ($file = readdir($handle))) {
if( substr( $file, 0, 1 ) != '.' ) {
if( is_dir( $path.'/'.$file ) ) {
listDir( $path.'/'.$file );
}
else {
if( #getimagesize( $path.'/'.$file ) ) {
/*
// Uncomment if using with the below "pic.php" script to
// encode the filename and protect from direct linking.
$url = 'http://domain.tld/images/pic.php?pic='
.urlencode( str_rot13( substr( $path, strlen( $startDir )+1 ).'/'.$file ) );
*/
$url='http://localhost/'.$path.'/'.$file;
substr( $path, strlen( $startDir )+1 ).'/'.$file;
// You can customize the output to use img tag instead.
echo "<a href='".$url."'>".$url."</a><br>";
echo "<img class='max-width' src='".$url."' />";
}
}
}
}
closedir( $handle );
} // End listDir function
$startDir = "assets/imagens/";
listDir( $startDir );
You can use RecursiveDirectoryIterator.
For example:
$directory = new RecursiveDirectoryIterator('assets/imagens');
$iterator = new RecursiveIteratorIterator($directory);
foreach ($entities as $name => $entity) {
if ($entity->isDir()) {
continue;
}
$extension = pathinfo($name, PATHINFO_EXTENSION);
if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif') {
echo '<img src="' . $entity->getPathname() . '" />';
}
}

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
}

How to get title from html file using directory - 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>";
}
}

Scandir Array display without file extensions

I'm using the following to create a list of my files in the 'html/' and link path.
When I view the array it shows, for example, my_file_name.php
How do I make it so the array only shows the filename and not the extension?
$path = array("./html/","./link/");
$path2= array("http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/html/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/link/");
$start="";
$Fnm = "./html.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
while( $file2 = readdir($folder2) ) {
if (substr($file2,0,strpos($file2,'.')) == substr($file,0,strpos($file,'.'))){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
fwrite($inF,"");
closedir($folder);
fclose($inF);
pathinfo() is good, but I think in this case you can get away with strrpos(). I'm not sure what you're trying to do with $imagename, but I'll leave that to you. Here is what you can do with your code to compare just the base filenames:
// ...
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
$fileBaseName = substr($file,0,strrpos($file,'.'));
while( $file2 = readdir($folder2) ) {
$file2BaseName = substr($file2,0,strrpos($file2,'.'));
if ($file2BaseName == $fileBaseName){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
I hope that helps!

PHP pull random image from folder

I am wondering about a "better" way of pulling a random image from a folder.
Like say, to have php just select a random image from folder instead of searching and creating an array of it.
here is how I do it today
<?php
$extensions = array('jpg','jpeg');
$images_folder_path = ROOT.'/web/files/Header/';
$images = array();
srand((float) microtime() * 10000000);
if ($handle = opendir($images_folder_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$ext = strtolower(substr(strrchr($file, "."), 1));
if(in_array($ext, $extensions)){
$images[] = $file;
}
}
}
closedir($handle);
}
if(!empty($images)){
$header_image = $images[array_rand($images)];
} else {
$header_image = '';
}
?>
Try this:
<?php
$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/<?php echo $images[$i]; ?>" alt="" />
Below code validate image list by image extension.
<?php
function validImages($image)
{
$extensions = array('jpg','jpeg','png','gif');
if(in_array(array_pop(explode(".", $image)), $extensions))
{
return $image;
}
}
$images_folder_path = ROOT.'/web/files/Header/';
$relative_path = SITE_URL.'/web/files/Header/';
$images = array_filter(array_map("validImages", scandir($images_folder_path)));
$rand_keys = array_rand($images,1);
?>
<?php if(isset($images[$rand_keys])): ?>
<img src="<?php echo $relative_path.$images[$rand_keys]; ?>" alt="" />
<?php endif; ?>
function get_rand_img($dir)
{
$arr = array();
$list = scandir($dir);
foreach ($list as $file) {
if (!isset($img)) {
$img = '';
}
if (is_file($dir . '/' . $file)) {
$ext = end(explode('.', $file));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG') {
array_push($arr, $file);
$img = $file;
}
}
}
if ($img != '') {
$img = array_rand($arr);
$img = $arr[$img];
}
$img = str_replace("'", "\'", $img);
$img = str_replace(" ", "%20", $img);
return $img;
}
echo get_rand_img('images');
replace 'images' with your folder.
I searched the internet for hours on end to implement the code to what I wanted. I put together bits of various answers I found online. Here is the code:
<?php
$folder = opendir("Images/Gallery Images/");
$i = 1;
while (false != ($file = readdir($folder))) {
if ($file != "." && $file != "..") {
$images[$i] = $file;
$i++;
}
}
//This is the important part...
for ($i = 1; $i <= 5; $i++) { //Starting at 1, count up to 5 images (change to suit)
$random_img = rand(1, count($images) - 1);
if (!empty($images[$random_img])) { //without this I was sometimes getting empty values
echo '<img src="Images/Gallery Images/' . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" />';
echo '<script>console.log("' . $images[$random_img] . '")</script>'; //Just to help me debug
unset($images[$random_img]); //unset each image in array so we don't have double images
}
}
?>
Using this method I was able to implement opendir with no errors (as glob() wasn't working for me), I was able to pull 5 images for a carousel gallery, and get rid of duplicate images and sort out the empty values. One downside to using my method, is that the image count varies between 3 and 5 images in the gallery, probably due to the empty values being removed. Which didn't bother me too much as it works as needed. If someone can make my method better, I welcome you to do so.
Working example (the first carousel gallery at top of website): Eastfield Joinery

Categories