PHP Formatted Date Links from files in a folder

Viewed 28

I am very inexperienced with PHP. I have a folder on a website which will receive files named with a numeric date structure. I need href links to be created for the files which are dropped into this folder. I need the link text to be formatted by with a textual month and numeric day. For example:

File name "01-02-22 BULLETIN.pdf" becomes

<href="bulletins/2022/$file">January 2</a>.

I have been messing with the code below from this post PHP to create Links for files in a folder, but I can't seem to figure it out. The links are appearing but any date formatting I attempt returns "error Call to a member function format()."

Thanks for your help!

<?php
                    $dir = "bulletins/2022/";

                    // Open a directory, and read its contents
                    if (is_dir($dir)){
                      if ($dh = opendir($dir)){
                        while (($file = readdir($dh)) !== false){
                          echo "<a href=bulletins/2022/$file>$file</a><br>";   
                    }
                    closedir($dh);
                    }
                    }
                    ?>
1 Answers

The html mark up is missing quotes

Here an example:

$some_path = "bulletins/2022";

$readdir=opendir($some_path);
while ($file = readdir($readdir))
{
if($file != '..' && $file !='.' && $file !='' && $file != ".htaccess")
{

echo "<a href=\"".$some_path."/".$file."\">$file</a><br>";  // yours is missing the quotes which should always be escaped in php with a backslash

}
}
closedir($readdir);

You could also concider using php time(); as the filename which will give you a unix timestamp which can then be sorted and converted into a date and time.

This example will sort the files in a natural order

$some_path = "demo_track_previews";

$readdir=opendir($some_path);
while ($file = readdir($readdir))
{
if($file != '..' && $file !='.' && $file !='' && $file != ".htaccess")
{
if(!empty(file))
{
$all_files[] = $file; //put all files in array ready to sort
}
}
}
closedir($readdir);

if(!empty($all_files))
{
sort($all_files,SORT_NATURAL);  //You can also try rsort($all_files,SORT_NATURAL);

foreach ($all_files as $key => $each_file)
{
echo "<a href=\"".$some_path."/".$each_file."\">".$each_file."</a><br>";
}

}

EDIT: after comment if you need just the date from the filename "01-02-22 BULLETIN.pdf" then try this

foreach ($all_files as $key => $each_file)
{
  $file_name_parts = explode(" ", $each_file); // seperate the filename where there is a space - $file_name_parts[0] will be 01-02-22

echo "<a href=\"".$some_path."/".$each_file."\">".$file_name_parts[0]."</a><br>";
}
Related