Ubuntu: Your Custom Command PHP Script

While it’s obvious for experienced users, I’m sure many newcomers to Linux might be wondering how to have a command like chmod, mv, ls, etc.

In other words, a command that accepts parameters, switches, and does interesting things in a language we all love and understand.

First of all, we’ll try phpLipsum, my newest CLI script. I wanted to have a way to access lipsum.com without any fancy GUI, just a quick command.

At YubNub.org they have online commands (very useful!), this command was the one I needed on my computer.

Handling the switches should be easy enough. We’ve seen this before, in previous articles. ;-)

$data = @file_get_contents($url) or die("\nError: Could not download the data.\n\n");
$xml = simplexml_load_string($data);

Once we have our URL built, we can make SimpleXML parse the XML for us. The text will be available through $xml->lipsum.

echo $xml->lipsum;

To make it a little bit easier on the eye I did this:

echo "\n    ".wordwrap(str_replace(".\n", ".\n    ", $xml->lipsum), 80)."\n\n";

This way, the text will be formatted nicely on the CLI. And the spaces shouldn’t affect its appearance on HTML!

Once our script is done, we make it executable. Remember how?

chmod +x lipsum.php

But I wanted to use it like this:

lipsum -a 2

So, we move it to /usr/bin/

sudo cp lipsum.php /usr/bin/lipsum

Note: You can move it (mv) or copy it (cp). I chose to copy it, so that I can keep a backup.

Now, we can finally have our own “command”! It’s quite easy and practical, and we haven’t abandoned our dear PHP. <3

Download phpLipsum


Tags: , , ,

%d bloggers like this: