PHP on the command line
PHP is the widest spread Web scripting language, that much is for sure.
However, PHP can also be used as a shell scripting language and help you agreat deal with your daily tasks on your server.
Here's a How to for all of you who use a *NIX system (BSD, Linux, Mac OSX and the likes). It works in windows as well but many tools re missing and I don't use Windows at all so I cannot speak about that.
Why should you use PHP as a shell scripting language?
- First of all, many of you will have knowledge in PHP but not in the common UNIX shells like csh, bash, zsh and the likes. So it will be easier for you to get started with scripting your server.
- Second, PHP scripts seamlessly integrate with your web projects. You can reuse your functions and classes in your command line scripts. For example, I use the FastSQL class a lot for my command line scripts that make database backups or fulfill reocurring tasks that require a database.
- Modern installs of PHP automatically have the module and the CLI (which is the command line-) version of PHP installed, you don't need anything more.
Depending on ypur build you will have either the CLI or CGI version of the php binary installed.
They are somewhat different in their behaviour but all these examples work with both of them.
If you can chose and you are using the php apache module for your web apps then take the CLI.
So, how does it work?
First, find out where your php binary lives.
On the command line, type
# which php
In my case (and on most standard installations) it gives back
/usr/local/bin/php
Now you are ready to write your first php command line script:
Script File
Save this as helloworld.php somewhere.
Now, make your file executable by changing to the directory where you saved your script and
write
# chmod 755 helloworld.php
Now, you call your script simply with
# ./helloworld.php
The result will look like this
Hello World
(Surprise!)
Now, let's look at the file.
The first line starts with a shebang (the "#!") followed by the path to your php binary followed by the option -q.
The shebang and the path take care that your script finds the php interpreter itself.
You can leave this out but then you'd have to type
# php ./helloworld.php
The -q flag tells php to not send a HTTP header in the CGI version.
Further on I'd like to show some useful practical examples for this.
If you're interested in the basics and theory have a look
PHP manual: Using PHP from the command line
|
|
|
Next:Passing variables to your script |