This is a very simple way to add files from a directory to your webpage in the form of a list or as links to the files. We'll create a folder named downloads where we add all our downloadable files (in my case I've just added two files dummy-file.txt and pretty-file.txt).
Then we use a build in PHP function called glob() which takes an argument with a pattern used to locate/filter the files. In this case we'll just make it look for all files by using the joker signature *.*, translated it means look for files with any name and any extension. And to look in the folder downloads we just write downloads/*.*, simple right?
Next we loop through each found file and echo out some HTML markup, in this case we make a simple link, like
<a href="file" download>file</a>where we simply replace file with the actual path, which in the loop will be stored in the variable $file:
PHP code
<?php
$files = glob("downloads/*.*");
foreach ($files as $file) {
echo "<a href='" . $file . "' download>" . $file . "</a><br>";
}
?>
HTML result
It works! But say we want to get rid of the folder name and just display the filename, how do we do that?
Well, an easy way to do that, is to replace downloads/ with "" (an empty string), so:
PHP code
<?php
$files = glob("downloads/*.*");
foreach ($files as $file) {
echo "<a href='" . $file . "' download>" . str_replace("downloads/", "", $file) . "</a><br>";
}
?>
Now, maybe it's just me, but I don't like that we have downloads/ hardcoded in two places. What if we changed the folder name to for example downlodables, then we would have to change downloads/ to downloadables/ in two places. An easy fix is to store the string in a variable:
PHP code
<?php
$folder = "downloads/";
$files = glob($folder . "*.*");
foreach ($files as $file) {
echo "<a href='" . $file . "' download>" . str_replace($folder, "", $file) . "</a><br>";
}
?>
The result is now a list of my two dummy files without the folder names, but the links still point at the correct path:
HTML result
The glob() function can do much more than just list all files. Let's try to list only .zip files:
PHP code
<?php
$folder = "downloads/";
$files = glob($folder . "*.zip");
?>
Let's try to list .zip files, .pdf files and .txt files.
This requires a second argument called GLOB_BRACE and an array of the extensions ({zip,pdf,txt}).
Be carefull to not add unnescessary spaces in the array, like {zip, pdf,txt}, in this case no .pdf
files will be found,
since it will be looking for *. pdf (notice the space):
PHP code
<?php
$folder = "downloads/";
$files = glob($folder . "*.{zip,pdf,txt}", GLOB_BRACE);
?>