Figured it was about time I actually posted something…
Little known to many people, PHP actually makes an excellent system level scripting language. Let's take a quick look at scrapping Perl & using PHP for a simple problem.
Setup:
I've got a bunch of m3u files that contain reference to single mp3 files on a friend's web server. I want to download all the mp3s, but don't want to open each m3u file & copy and paste the http link. Let's use PHP for the task.
First off, this depends on how you have PHP installed, esp. on Linux/Unix systems. If PHP is installed as an apxs Apache module, then you will need have an additional install of PHP. Luckily, this is easy. Download PHP, & enter the source directory & just run "./configure" with no options. This will configure PHP to install binaries under "/usr/local/lib/" and will not touch your existing Apache installs. Windows users would just have to make sure the PHP install dir and php.exe is in your path.
I'm running this script on a Unix system, so I can make use of an excellent utility called wget, which is a command line utility to download files via HTTP and is very configurable.
On with the script!
// Define the path to the files you want to download from
$dirpath="/usr/wget/mydir/audio/";
// Options for wget may vary.. use wget –help
$command="wget -o errors.wget -c ";
// List all files in the dir. Swipped from php.net
if ($handle = opendir($dirpath)) {
// Recurse over $dirpath & get a pointer to each handle
while (false !== ($file = readdir($handle))) {
// Check its a file, and match to your pattern
// (if you have multiple file types in the dir)
// fnmatch() is available only in PHP >= 4.3.0
if (is_file($file) && fnmatch("*m3u", $file)) {
// file_get_contents PHP >= 4.3.0
$url=file_get_contents($file);
// Be careful using system() in web scripts
system($command.$url);
}
}
// Don't forget to close the handle
closedir($handle);
}
Notes: This is run from the command prompt by: php filename.php
This invokes the PHP interpreter & runs the script.
Its a simple script, but could easily be adapted to renaming a large number of files, displaying the contents of many files, etc. PHP has pretty good string & file handling functions (and getting better with each release).
For hardened Perl users, PHP looks in its infancy, but for simple system tasks, why not use your PHP skills?