List and link php files in a folder and its metatag description

Therefore, to sum up, maybe it is impossible to “merge” glob and get_meta_tags, isn’t it?
And, if so, there is another way to reach my aim (add automatically a description to each file of an automatic list)?

its certainly not impossible.
what do you get if you print_r(get_meta_tags(glob("php-read-exif.php")[0])); ?

Well, that’s confused matters. I just copied the first section of your code from post 18, reproduced below, and for the one PHP file that I have in my directory that has any meta data, I get a result.

The code:

<?php
    echo "<ul>";	  
$phpfiles = glob("*.php");

var_dump($phpfiles);

foreach ($phpfiles as $phpfile){
    echo '<li><a href="'.$phpfile.'">'.pathinfo($phpfile, PATHINFO_FILENAME).'</a>';
    echo "<span>";}
foreach ($phpfiles as $files){
    echo "<p><b>$files</b></p>";   //just for testing it
    $tags = (get_meta_tags($files));
    var_dump($tags);
    echo PHP_EOL;
    echo "</span></li>"; 
}
?>

And the result:

paginationtest.php

C:\wamp64\www\sitepoint\gmttest.php:14:
array (size=1)
  'viewport' => string 'width-device=width, initial-scale=1' (length=35)

and the relevant bit of that file:

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width-device=width, initial-scale=1">
</head>
<body>

I still don’t think we’ve seen the content of one of the files that you’re examining with get_meta_tags(), have we? Only the two lines of meta data, but not the context they sit in.

You don’t have a closing </head> tag before your meta tags, by any chance?

I wish I’d thought of this sooner, but a key difference between accessing the files via their URL, and accessing them as files, is that by accessing the URL you will be seeing the output after your PHP code has been executed. Accessing them as files will examine your PHP source code. Does that make any difference to the expected result?

In other words, is the meta-tag information at the top of these PHP files, in HTML form (NOT enclosed in PHP tags, not echoed out, etc), at the top of the file before the </head>?

get_meta_tags is definitely expecting HTML, but it will stop reading at </head>. So if the PHP is further down the page, i would expect it to work as normal. If there is PHP anywhere before the end of the header… I think droop’s right, it’ll cause problems.

That said; all hope is not lost, you would just have to use another mechanism (probably some regex parsing) other than get_meta_tags.

Yes, we have #18 (List and link php files in a folder and its metatag description - #18 by web148).

what do you get if you print_r(get_meta_tags(glob("php-read-exif.php")[0])); ?

this: Array ( )

is the meta-tag information at the top of these PHP files, in HTML form (NOT enclosed in PHP tags, not echoed out, etc), at the top of the file before the </head> ?

no, it is “enclosed in PHP tags”, as you can see at the top of the code #18

Eh… it gets messy… At that point i’m just slicing out the string.

function get_description_variable_from_php_file($filename) {
    $data = file_get_contents($filename);
    return (preg_match('~$description\s*=\s*"(.*?)"~',$data,$match)) ? $match[1] : "Description not found";
  }
$results = array();
array_walk(glob("*.php"),function ($x) {
if($x = "index.php") { continue; }
$results[$x] = get_description_variable_from_php_file($x); 
});
1 Like

@web148,

It looks as though certain meta tags are expected and frequently they are not declared which produces errors.

At the moment I’m busy with with another project and had to validate URLs and surprised after a lengthy search I could not find an easy solution. The solution I liked for validating URLs, online images, etc:

<?php declare(strict_types=1); // this file wide type checking
error_reporting(-1); // display maximum errors
ini_set('display_errors', 'true'); // show errors on screen

$url = 'https://thoughfuldigitalworld.000webhostapp.com';

echo '$url ==> ' .$url;

if( validateUrl($url) ) :
  if(0) :
    $aTmp   = get_headers($url);
    echo '<pre> get_headers($url) ==> '; print_r($aTmp); echo '</pre>';
  endif;  

  $aTags  = get_meta_tags($url); 
  # echo '<pre> get_meta_tags($url) ==> '; var_dump($aTags);
  if($aTags) :
    echo getMetaTags($aTags);
  else:
    echo 'Yes we have no $aTags[]';
  endif;    
else:  
  echo '<br><br> Invalid URL ???';
endif;  


// ONLY FUNCTIONS BELOW


//======================================
function validateUrl( string $url = 'https://sitepoint.com' )
: bool  
{
  $result = FALSE;

  if ($url == NULL)
  {
      return $false;
  }
  $ch = curl_init($url);
  
  curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $data     = curl_exec($ch);
  $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

  curl_close($ch);

  $result = ($httpcode >= 200 && $httpcode < 400) ? true : false; 

  return $result;
}

//======================================
function getMetaTags( array $aTags=[] )
: string
{
  $result  = '';
  
  $result .= '<hr> <table style="text-align: left;">';
    $result .= '<tr style="background-color: #ddd;"><th> Meta tag </th> <th> String </th> </tr>';
    foreach($aTags as $meta => $string)
    {
      $result .= 
          '<tr><td> <b>' 
          .  $meta
         .'</b> </td> <td>' 
         .   ' &nbsp; '. $string 
         .'</td> </tr>'
         ;
    }
  $result .= '</table> <hr>';

  return $result;
}
1 Like

Thank you, @John_Betong. Your code works to get meta tags of the index file, but not to list and link all php files, doesn’t it?
But it could be an important step.

Uhm, in effect, this code doesn’t work:

**Fatal error** : 'continue' not in the 'loop' or 'switch' context in

I’m not sure of your requirements.

Do you want a function to accept a path and return an array of every PHP in the path and all sub-directories?

I wish to get a list of all php files of a folder (not subfolder), linked (and this is already possible), and a description (from the meta tag description) at the right side of every file name (a table could be a good solution: left column the names of the files, with its link, and right column the description of every file, from its meta tag “description”).
Something like:

  • myfile1 - this file, bla bla bla
  • myfile2 - this other file, bla bla bla

OK, now I understand :slight_smile:

Please check the Free PHP Online Manual and notice that glob(…); expects the first parameter to be a path/directory and not an URL.

https://www.php.net/manual/en/function.glob.php

Get all .php files in a directory and display files with a description meta tag.

<?php declare(strict_types=1); // this file wide type checking
error_reporting(-1); // display maximum errors
ini_set('display_errors', 'true'); // show errors on screen

echo '$path ==> ',
  $path = '/var/www/john-betong.tk/public_html';

$aTmp = glob($path .'/*.php');
  foreach($aTmp as $key => $file):
    $aTags  = get_meta_tags($file);
    $description = $aTags['description'] ?? NULL;
    if($description) :
      echo '<dl>';
      echo    '<dt> $file ==> ' .$file .'</dt>';
      echo    '<dd> &lt;meta&gt; description = "' .$description .'"&gt;</dd>';
      echo    '<dd>';
      echo      '<pre> <b>All the $aTags </b> ==> ';
                    print_r($aTags);
                    # <meta charset="UTF-8">
      echo      '</pre>';
      echo    '</dd>';
      echo '</dl><br>';
    endif;  
  endforeach;


// ONLY FUNCTIONS BELOW


//======================================
function getMetaTags( array $aTags=[] )
: string
{
  $result  = '';
  
  $result .= '<hr> <table style="text-align: left;">';
    $result .= '<tr style="background-color: #ddd;"><th> Meta tag </th> <th> String </th> </tr>';
    foreach($aTags as $meta => $string)
    {
      $result .= 
          '<tr><td> <b>' 
          .  $meta
         .'</b> </td> <td>' 
         .   ' &nbsp; '. $string 
         .'</td> </tr>'
         ;
    }
  $result .= '</table> <hr>';

  return $result;
}//

//======================================
function vd( $val, $vd=FALSE )
{
  echo '<pre class="w88 mga"> <br><br><hr>';
  if($vd):
    print_r($val);
  else:
    var_dump($vd);  
  endif;  
  echo '</pre>';
}//  

Beware:

The php glob(…); function is case-sensitive.

Screendump

web148-2021-05-29 17-27-01

1 Like

John, are your test files hardcoded html meta tags?
See post 18 for an example of his files.

1 Like

Thank you, John. But the path should be a file or can be a folder?
If I set a folder I see only “.” or “/”, but no files at all …

But there aren’t any meta-tags in that code, which is why your code isn’t finding them. On first look, that code appeared to be the code you are using to read the metatags, not the code that should contain them.

at #26 I said: no, metatag is “enclosed in PHP tags”, as you can see at the top of the code #18, that is
$description="ricavare metatags";
and in the linked header-intell.inc there is this line:

<meta name="Description" content="<?php echo $description; ?>" />

Edit:

Finally understand the requirements :slight_smile:

Please note the **$path** can be easily changed and is passed as a parameter to glob(…) with the file mask to obtain all the files in the $path directory.

As far as not displaying index.php is concerned and also case-sensitive I would used the following script:

<?php 
declare(strict_types=1); // this file wide type checking
error_reporting(-1); // display maximum errors
ini_set('display_errors', 'true'); // show errors on screen


echo '$PATH ==> ',
  $PATH = '/var/www/john-betong.tk/public_html/'
        . '*.*';

$result = ''; // return a string of all files containing 'description'

$aTmp = glob($PATH); // receive every file in the $path directory
// vd($aTmp);

  foreach( $aTmp as $key => $file )
  {
    
    $sLowercase = strtolower($file) ;
    if('index.php'===$sLowercase)
    {
      echo '<h2> Do not use: '  .$file .'</h2>' ;

    }else{
      if( strpos($sLowercase, '.php') ) 
      {
        // echo '<br>' .$file;;
        $aTags  = get_meta_tags($file);

        // Prevent index not found error
        $description = $aTags['description'] ?? FALSE ;
        if($description) 
        {
          $result .=  '<dl>';
          $result .=  '<dt> <b> FILE [meta]: </b> ' .$file .'</dt>';
          $result .=   '<dd> &lt;meta&gt; description = "' .$description .'"&gt; </dd>';
          $result .=  '</dl>';
        }//endif($description) 
        $hasDescription = getDescription($file);
        if( strlen( $hasDescription ) )
        {
          $result .= $hasDescription;
        }
      }//endif strpos(...);  

    }//endif('index.php'===$sLowercase)

 }//endforeach

if( strlen($result) )
{ 
  echo $result;
}else{ // must be empty
  echo '<h2> There are no PHP files with containing a meta [description] </h2>';
}// endif

echo '<h3> Finished processing </h3> ';


// ONLY FUNCTIONS BELOW


//======================================
function getDescription( string $file)
: string 
{
  $result = ''; // eEMPTY IF FALSE

  $contents = file_get_contents($file);
  $iStart   = strpos( $contents , "\$description");
  if( $iStart ) 
  {
    $tmp    = substr($contents, ++$iStart) ;
    $tmp2   = strpos($tmp, ';');

    $result = '<dl>'
            . '<dt> <b> File $description ==> </b> ' 
            .     $file 
            . '</dt>'
            . '<dd>'
            .   substr($contents, $iStart, $tmp2)
            .'</dd></dl>'
            ;
  }// endif;

  return $result;
}//


//======================================
function vd( $val, $vd=FALSE )
{
  echo '<pre class="w88 mga"> <br><br><hr>';
  if($vd):
    print_r($val);
  else:
    var_dump($vd);  
  endif;  
  echo '</pre>';
}//  

Edit:

**File: TEST.php

<?php DECLARE(STRICT_TYPES=1);
error_reporting(-1);
ini_set('display_errors', '1');
session_start();

# echo '<h1> John-Betong.tk </h1>';
$title = 'title goes here would you believe';
$description = 'JUST TESTNG TO SEE IF IT WORKS';


?>
<!doctype html><html lang="en">
<head>
<title> HTML5 Local Storage Project </title>
<meta charset="UTF-8">
<meta name="description" content="<?= $description ?>">
<meta name="viewport"    content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta NAME='rating'      content='General' />
<meta NAME='expires'     content='never' />
<meta NAME='language'    content='English, EN' />
<meta name="author"      content="dcwebmakers.com">

<script src="assets/js/Storage.js"></script>
<link rel="stylesheet" href="assets/css/StorageStyle.css">

Output:

Screenshot from 2021-05-30 14-55-30

1 Like

Thank you, John. I tested your code.
Your code works, with a PC path (not beginning with http://).
But in this way, could I use it on a remote website?

The PHP Manual:

Notes

Note : This function will not work on remote files as the file to be examined must be accessible via the server’s filesystem.

Edit:

The script will work on a remote server but must be called from the same remote server. Calling the script from a local server with an URL will not work.

1 Like