This snippet comes in handy and has saved me hours of menial coding tasks. Let’s say you have a customer that you do a lot of work for and you want them to access certain files. In my case, I produce and edit a lot of TV commercials for clients. I never hard code their “download portal”, because it’s a waste of time, simply upload your files via ftp to a folder and put this snippet in your index.php file along with other messaging to your customers.
This procedural code can be inserted anywhere to automatically generate a clickable list of files for your customers.
Here’s the PHP snippet that will save you lots of time later:
<?php $s=scandir("."); foreach ($s as $file){ // replace ".mp" with the file extension you want to allow through this filter -- this loop will ignore any other file extension. if (stristr($file,".mp")){ $file_title=str_replace("_"," ",$file); // This displays a nice "Title Without Those Ugly Underscores" echo "<a href='$root$file' style='margin:5px'>$file_title</a><br/><br/>"; } } ?>
You might also want to force files of a certain extension to be download only by default, this is often done by adding this line to the .htaccess file either site wide or in the individual folders you wish:
Add to .htaccess to force download of file extensions instead of the browser possibly trying to open the file and displaying it inside its window. Just simply add the file extension to the list below, much like I added “mp4” at the end of the list. Keep the same pattern by separating each file extension with the pipe (|) delimiter.
Also keep in mind the module mod_headers needs to be loaded in Apache2, this is a common module that is usually enabled by default by most web hosts, but do not assume.
<filesmatch "\.(?<span="" pre="">i:doc|odf|pdf|cer|txt|mp4)$"> Header set Content-Disposition attachment </FilesMatch>