I have a folder on my server that will receive monthly drops of newsletter files. These drops will occur automatically and I've been asked to write something in PHP to display the list of files as downloadable links while changing the display named based on the name of the file.
The folder I'm looking to is "/var/newsletters" and I'm including code on the index.php page at the root directory. The code I have so far is this:
<?php
$dir = "var/newsletters/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>
This does display the list of files, but it's only the first step of the process. They are not linked and they are not renamed. These are monthly newsletter files and are named nmmyyyy.pdf (For example, September would be n092017.pdf). What I need to do is convert n092017.pdf to "September 2017" and then create the link, so something like n092017.pdf and n102017.pdf in the directory becomes
<ul>
<li><a href="var/newsletters/n092017.pdf">September 2017</a></li>
<li><a href="var/newsletters/n102017.pdf">October 2017</a></li>
</ul>
I've looked at a few links here:How to list files and folder in a dir (PHP) and List all files in one directory PHP, but found that the code I showed above worked best. What I need help with is displaying the list as links and converting the names. Thank you!
EDIT: I was able to get teh link to work with this code:
<?php
$dir = "var/newsletters/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo " <a href=var/newsletters/$file>Click here</a><br>";
closedir($dh);
}
}
?>
I'm now working on changing the file name and that is not displaying properly. I'm currently working with it as:
<?php
$dir = "var/newsletters/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "<a href=var/newsletters/$file>
function getDateFromFileName($filename){
$dateObj = DateTime::createFromFormat('m-
Y',substr($filename,1,2).'-'.substr($filename,3,6));
return $dateObj->format('F Y');
}
</a><br>";
}
closedir($dh);
}
}
?>
EDIT 2
<?php
$dir = "var/newsletters/";
function getDateFromFileName($filename){
$dateObj = DateTime::createFromFormat('m-Y',substr($filename,1,2).'-'.substr($filename,3,6));
return $dateObj->format('F Y');
}
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
//echo $file . "<br>"; OR //echo "<a href=var/newsletters/$file>Click here</a><br>"; WORKING
$formatted_date = getDateFromFileName($file);
echo "<a href=var/newsletters/$file>{$formatted_date}</a><br>";
}
closedir($dh);
}
}
?>
"; with the exception that I have an extra "/" at the end of the file name which causes the link to break. – M. Baile Oct 14 '17 at 18:58