automatize your website

Recently I managed to make some new improvements about website automation

After the automation of gallery, in a previous post, I did this other automation (with php):

list php pages with a given name

With the following code, you can list (and link) all webages php files containing in its filename the variable you can set:

<?php
echo "<h3>testi on-line di $autore</h3>";
echo "<ul class=\"flexmenu\">\n";

// Escape special characters in $autore to use safely in glob pattern
$phpfiles = glob("$path/*" . preg_quote($autore_di, '/') . "*.php"); // Get all PHP files with $autore in the name

foreach ($phpfiles as $phpfile) {
    $contents = file_get_contents($phpfile);

    preg_match('/\$title\s*=\s*"(.*?)";/', $contents, $titleMatch);
    preg_match('/\$subtitle\s*=\s*"(.*?)";/', $contents, $subtitleMatch);
    preg_match('/\$description\s*=\s*"(.*?)";/', $contents, $descriptionMatch);
    preg_match('/\$order\s*=\s*"(.*?)";/', $contents, $orderMatch);

    $title = $titleMatch[1] ?? 'No title';
    $subtitle = $subtitleMatch[1] ?? 'No subtitle';
    $order = $orderMatch[1] ?? '';
    $description = $descriptionMatch[1] ?? 'No description';

    // Correctly extract the filename
    $filename = $phpfile; // Use basename on $phpfile directly

    echo " <li role='menuitem' style=\"order:$order\"><a href=\"{$filename}\">{$title}</a>, <i>{$subtitle}</i>: {$description}</li>\n";
}

echo "</ul>";


echo "<h3>testi on-line su $autore</h3>";
echo "<ul class=\"flexmenu\">\n";

// Escape special characters in $autore to use safely in glob pattern
$phpfiles = glob("$path/*" . preg_quote($autore_su, '/') . "*.php"); // Get all PHP files with $autore in the name

foreach ($phpfiles as $phpfile) {
    $contents = file_get_contents($phpfile);

    preg_match('/\$title\s*=\s*"(.*?)";/', $contents, $titleMatch);
    preg_match('/\$subtitle\s*=\s*"(.*?)";/', $contents, $subtitleMatch);
    preg_match('/\$description\s*=\s*"(.*?)";/', $contents, $descriptionMatch);
    preg_match('/\$order\s*=\s*"(.*?)";/', $contents, $orderMatch);

    $title = $titleMatch[1] ?? 'No title';
    $subtitle = $subtitleMatch[1] ?? 'No subtitle';
    $order = $orderMatch[1] ?? '';
    $description = $descriptionMatch[1] ?? 'No description';

    // Correctly extract the filename
    $filename = $phpfile; // Use basename on $phpfile directly

    echo " <li role='menuitem' style=\"order:$order\"><a href=\"{$filename}\">{$title}</a>, <i>{$subtitle}</i>: {$description}</li>\n";
}

echo "</ul>";
?>

You can call that code in a webpage, with something like this:

<?php
/*files beginning with i must be uppercase */
$path="../testi";// your path
$autore="Aristotele";
$autore_di="Aristotele[di]";//texts of $autore
$autore_su="Aristotele[su]";//texts about $autore
include "$root/lista-files-testi-[autore]-online-con-metatags.inc";
?>

automatically list files in a website menu

You can create an automatic menu list of your files in a given folder, and in a folder with the same name of one file (without extension, of course). With a code like the following:

<?php
$phpfiles = glob("{$root}/$menupath/[^index]*.php");

foreach ($phpfiles as $phpfile) {
  $contents = file_get_contents($phpfile);

  // Match $order
  preg_match('/\$order\s*=\s*"(.*?)";/', $contents, $orderMatches);

  // Match $title
  preg_match('/\$title\s*=\s*"(.*?)";/', $contents, $titleMatches);

  // Assign the values
  $order = $orderMatches[1] ?? null;
  $title1 = $titleMatches[1] ?? null;

  $filename1 = basename($phpfile); // Get only the file name
  $filename = pathinfo($phpfile, PATHINFO_FILENAME);
  $filename = str_replace('-', ' ', $filename); // Replace hyphens with spaces in the filename
  $filename = ucfirst($filename); // Optional: Capitalize the first letter for better readability
  $link = "$root/$menupath/{$filename1}"; // Create the relative link

  // Start the list item for the menu
  echo "<li role='menuitem' style=\"order:$order\"><a href=\"{$link}\">{$title1}</a>";

  // Check if a sub-menu is required (look for a folder matching the filename)
  $folder = "{$root}/$menupath/{$filename}";
  if (is_dir($folder)) {
    // If the subfolder exists, generate the sublist automatically
    $subfiles = glob("{$folder}/[^index]*.php");
    if (count($subfiles) > 0) {
      echo "<ul class='flexmenu'>"; // Start sublist
      foreach ($subfiles as $subfile) {
        $subfileName = basename($subfile);
        $subfileTitle = pathinfo($subfile, PATHINFO_FILENAME);

        // Match $order for subfiles
        $subfileContents = file_get_contents($subfile);
        preg_match('/\$order\s*=\s*"(.*?)";/', $subfileContents, $subfileOrderMatches);
        $subfileOrder = $subfileOrderMatches[1] ?? null;

        // Remove hyphens and add colon after the main part of the title
        $subfileTitle = str_replace('-', ' ', $subfileTitle);

        // Separate the main part (before the colon) and the rest of the title
        $parts = explode(' ', $subfileTitle, 2); // Split into two parts: main and description
        $mainPart = $parts[0]; // This is the first word (e.g., "Aristotele")
        $description = isset($parts[1]) ? $parts[1] : ''; // Everything after the first space (e.g., "l etica")

        // Combine the main part with colon and the description
        $formattedTitle = ucfirst($mainPart) . ": " . $description;

        $subfileLink = "$root/$menupath/{$filename}/{$subfileName}";
        echo "<li style=\"order:$subfileOrder\"><a href=\"{$subfileLink}\">{$formattedTitle}</a></li>";
      }
      echo "</ul>"; // End sublist
    }
  }
  // End the list item for the menu
  echo "</li>\n";
}
?>

That you can call in a place of the whole menu with a code like this:

 $menupath="your/relative-path";
 include "menu-automatic.inc"; 

Where menu-automatic.inc is the name of the file containing the above code.

php include: no absolute path

To get include command working you should avoid an absolute path: i.g. not

http://somepath/somefile

But, i.g.:

../somepath/somefile

2) In localhost it would be possible this workaround:

$yourvariablepath = realpath($_SERVER["DOCUMENT_ROOT"] . "/a/path");

But this doesn’t work in remote.

3) Another workaround to include a content from a file in another absolute path could be the object tag:

<object data=”your-file-even-on-another-server” />

But an object in another page is an island, a stranger “guest”, without any sharing with the “host” page.

4) Another way (for short text) is to use javascript.

how to pass a php variable to javascript

You can use a code like the following:

<?php 
  $name= "Hello World";
?> 
<script> 
  var x = "<?php echo "$name"?>";      
  document.write(x);    
</script>

and then insert this code in a php page: but not with a js extension, but with some like inc

php show a content in a given period of the year

You can use a very simple php code, f.e. for Christmas and Happy New Year greetings:

<?php 
$dataattuale = date('m-d');
$inizioauguri = date('m-d', strtotime("11/13"));
$finauguri = date('m-d', strtotime("01/10"));  
if (($dataattuale >= $inizioauguri) && ($finauguri <= $finauguri))
{include "$root/natalizio.php";} 
?>

The above code show the content of natalizio.php (in root folder) from November 13th to January 10th.

Another example

$now = date('Y-m-d');
$end = date('2024-07-15');  
if ($now <= $end)
{echo "some text";}

php list and link folder’s files

an old way

There is an old way, the following:

<?php
     $path = "./";
     $narray=array();
     $dir_handle = @opendir($path) or die("Unable to open $path");
     echo "";
     $i=0;
     while($file = readdir($dir_handle))
     {
     if($file != '.' && $file != '..' && $file != 'index.php' && $file != 'normal.inc')
     {
     //echo "<a href='$path/$file'>$file</a><br/>";
     $narray[$i]=$file;
     $i++;
     }
     }
     sort($narray);

	   echo "<ul>";	            
     for($i=0; $i<sizeof($narray); $i++)
	   {
	    $filename = str_replace(".html", "", $narray[$i]) & str_replace(".php", "", $narray[$i]);
	   echo "<li><a href='$path$narray[$i]'>$filename</a></li>";
	   }
	   
	   echo "</ul>";
	   //closing the directory
	   closedir($dir_handle);
?>

a new way: glob

<?php
	   echo "<ul>";	  
$phpfiles = glob("[^index]*.php");
foreach ($phpfiles as $phpfile){
     echo '<li><a href="'.$phpfile.'">'.pathinfo($phpfile, PATHINFO_FILENAME).'</a></li>'; 
}	   
	   echo "</ul>";
?>

as you can see, the code is much simpler.

  • With this code: glob(“[^index]*.php”) we have set to list all php files except index.php.
  • with this other: ‘.pathinfo($phpfile, PATHINFO_FILENAME).’ we have set to show only filenames without extension

of course we could set a subfolder as well, with a code like the following:

$phpfiles = glob("[subfolder-name]/[^index]*.php");

php/msql keywords as hashtags

php separate all items in a mysql field

You can use the explode syntax, as in the following exapmple:

$keywords = $row['keywords'];
foreach (explode(',', $keywords) as $key) {
    echo "<span><a href="\hashtag.php?tag=$key\">{$key}</a></span>";
}

In the example we have a mysql field (keywords) with many items comma separated (such as : “truth, soul, body, mind” and so on).

And we obtain to have as many links from each item toward a specific target, as they are (that is: 3 links if you have 3 items, 7 links fi you have 7 ones).

In this way you can get a system of hashtags for your database keywords.

other steps

You need another file, let we call them hashtag.php.

The content of hashtag.php could be something like:

<?php  
 //hashtag.php  
 if(isset($_GET["tag"]))  
 {  
      $tag = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '', $_GET["tag"]);

//to beautify and stylize, but not necessary BEGIN
      $title=$tag;
      include "$root/intell/header-intell.inc";      
//to beautify and stylize, but not necessary END      

      $connect = mysqli_connect("localhost", "[mysql user]", "[mysql password]", "[mysql database]");  
      
      mysqli_set_charset($connect, 'utf8mb4');  // procedural style
      
      $query = "SELECT * FROM [your table] WHERE [your fields with tags] LIKE '%".$tag."%';  
      $result = mysqli_query($connect, $query);  
      if(mysqli_num_rows($result) > 0)  
      {  
           while($row = mysqli_fetch_array($result))  
           {  
                echo "<h2>$row[title]</h2>
                <blockquote><p>$row[text]</p></blockquote>
                <p><i>$row[author]</i><br />";
                $keywords = $row['keywords'];
                foreach (explode(',', $keywords) as $key) {
                if(trim($row["keywords"])==''){echo "";} else{echo "<span><a href=\"hashtag.php?tag=$key\">{$key}</a></span>";}
                }
                echo "</p>";
           }  
      }  
      else  
      {  
           echo '<p>No Data Found</p>';  
      }  
 }  
 ?>  

Afterwards obviously you could adjust the css according to your needs.

Of course you can have as many other php files as you want, where you usually store you database content, in which you can add the kewwords as hashtags, with a code like the following:

echo "</p><p class=\"keywords\">";
$keywords = $row['keywords'];
foreach (explode(',', $keywords) as $key) {
    if(trim($row["keywords"])==''){echo "";} else{echo "<span><a href=\"hashtag.php?tag=$key\">{$key}</a></span>";}
}
echo "</p>";}

batch change encoding to UTF-8 for several text (php) files

You can use recode
recode UTF-8 *.php -v

provided that all the files have the same encoding.
Otherwise you can try with something like
iconv -f US-ASCII -t UTF-8 *.php

a minor problem

It could be an apparent problem if there aren’t non-ascii characters in a file: then these files are yet recognized, with
file -i --mime-encoding *
as us-ascii.
So you can add a non ascii character, like è:
sed -i -e “$aè” *.php

and afterwards redo the command “recode” as above and replace some ascii expression, like agrave; with UFT-8 à character.
Eventually you will delete the “è” from the end of the files.