LanguagesPHPSystem Administration with PHP

System Administration with PHP

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

As many of you would surely attest, once you start developing with PHP it’s pretty difficult to consider another language for your daily Web development activities. This isn’t surprising, given PHP’s relatively shallow learning curve, the literally thousands of readily available predefined functions, and the seemingly endliness array of projects and user groups sprouting up all over the globe. Wouldn’t it be great if you could extend your use of the language to carry out general system administration tasks? You might be surprised to learn that you can! In this article, I’ll show you how to create PHP scripts that can execute from the command-line. Once I’ve introduced a few basic concepts, I’ll demonstrate how to write PHP scripts that can carry out useful administration tasks.

The Basics

The Web server is responsible for processing requests and returning output to the client. Yet, the server isn’t always capable of processing the request on its own, and depends upon a host of other tightly integrated technologies such as PHP and Perl for carrying out operations such as assembling page components, querying databases, and managing user sessions. For example, the ApacheWeb server knows when it must pass along a requested page to a third-party technology by examining the resource extension. For example, if the requested resource is the file index.php, and Apache has been configured to pass all resources with the extension .php to the PHP engine, then Apache will do so and wait for the result to be returned before responding to the client.

Although many have attempted to use PHP as the “golden hammer” in the past, this strategy often proves highly inconvenient simply because server-based tasks were simply never meant to run over extended periods of time. However, as of PHP version 4.2.0, it’s possible to directly invoke the PHP engine by calling it from the operating system command-line, available via a new SAPI type known as the CLI (Command Line Interface). This new capability opens up the possibility for system administrators to use PHP for managing various server-related tasks, among which include duties pertinent to managing system backups, monitoring system resources, and parsing logs. This capability was disabled by default until version 4.3.0; therefore, if you’re using a version 4.2.X version, you’ll need to explicitly enable it by using the –enable-cli option at configuration time.

To determine whether your installation is capable of executing via the command-line, locate the PHP binary and execute it like so:

%>/usr/local/bin/php -v

For example, my PHP 5 installation returns:

PHP 5.0.0RC1 (cli) (built: Mar 18 2004 18:20:03)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v2.0.0RC1, Copyright (c) 1998-2004 Zend Technologies

You can view a complete list of options made available via this new CLI by executing the following command. I suggest doing so, as there are quite a few unexpected options that you may find quite useful.

%>/usr/local/php -h

In the next section, I’ll demonstrate a few real-world administration scripts that you might consider incorporating into your own toolset.

A Simple Example

For starters, let’s consider a simple yet useful example. I regularly work with colleagues based out of offices located in both GMT and PST time zones, and we’re always calculating zone variations when suggesting meeting times for online chat conferences. Because I’m lazy, I wrote the following script that calculates the time differences, titled timezone.php:

<?php
$christz = 0;      // GMT
$jasontz  = -5;    // GMT -5
$julietz = -8;     // GMT - 8

echo "Jason: ".gmdate("h:i:sa", time() +
              3600*($jasontz+date("I")))."n";
echo "Chris: ".gmdate("h:i:sa", time() +
              3600*($christz+date("I")))."n";
echo "Julie: ".gmdate("h:i:sa", time() +
              3600*($julietz+date("I")))."n";
?>

The script timezone.php can be executed from the command-line like so:

%>php timezone.php

Sample output follows:

Jason: 10:41:27pm
Chris: 03:41:27am
Julie: 07:41:27pm

If you’ve created Perl, Python, or shell scripts in the past, this process should be quite familiar to you. However, you may have noted a few differences, several of which I’ll outline here:

  • Is the .php extension required? Nope. Because I use a blend of PHP, Perl, and shell scripts for administration, I prefer to retain the extension simply for sake of organization.
  • Where’s the shebang? Readers familiar with typical Perl and shell scripting are familiar with the #! reference on the first line, also known as the “shebang.” The shebang is followed by the path leading to the scripting executable, /usr/bin/perl for example. In fact, you can do this with PHP, and forego the explicit reference to the PHP executable on the command-line; I prefer to do so in order to eliminate platform-compatibility issues.

Redirecting Output

Although its useful to view script output from the terminal, you may wish to redirect this data to a textfile or even send it to somebody via e-mail. Both output variants are easily accomplished. In this section, I’ll show you how both tasks are easily accomplished.

Redirecting Output to a Text File

Because we’re dealing with shell-based scripting, we can take advantage of the full range of Unix redirection capabilities. For example, suppose that you’d like to redirect output from the timezone.php script to a file named output.txt:

%>php timezone.php > output.txt

Executing this command, you’ll see that a file named output.txt has been created, with output contents identical to those found in the previous example. In the next installment of this series, I’ll introduce a somewhat more sophisticated mechanism for redirecting script input and output, so be sure to stay tuned for more information on this topic.

Redirecting Output to an E-Mail

Just like my morning cup of coffee, I cherish the ability to have various statistics and other server information e-mailed to me for review at the beginning of each workday. I’ve long done so with my Perl and shell scripts, and now do the same with my PHP scripts, a feat easily accomplished using PHP’s mail() function. Let’s revise the original timezone.php script, calling it timezone-email.php, this time sending the output to my e-mail address (my address a tad obfuscated to fool annoying spammers):

<?php
$jasontz = -5; // GMT -5
$christz = 0; // GMT
$julietz = -8; // GMT - 8

$output = "Jason: ".gmdate("h:i:sa", time() +
                            3600*($jasontz+date("I")))."n";
$output .= "Chris: ".gmdate("h:i:sa", time() +
                             3600*($christz+date("I")))."n";
$output .= "Julie: ".gmdate("h:i:sa", time() +
                             3600*($julietz+date("I")))."n";

mail("wjATwjgilmore.com","My Colleagues' Local Time", $output);
?>

Change the address, and execute this script in the same fashion as in the first example. After a few moments, the e-mail should arrive in your inbox.

Scheduling Script Execution

While manual script execution is useful when you’re in immediate need of a result, system administration often requires for information to be provided on a highly repetitive, regular basis. Because human nature dictates that we’ll soon fail to follow such a stringent schedule, it’s wise to simply automate script execution, redirecting output to either a flatfile to be examined at the administrator’s leisure, or better, to an e-mail address. On Unix systems, such automation is often accomplished using the CRON feature. CRON is capable of scheduling a job on a periodic basis, and provides you with the means for determining the timeframe. Because there are several great CRON tutorials available on the Web, I’ll forego an introduction, and instead move directly to implementation details. Suppose that I want to receive the results of the timezone-email.php script via e-mail each morning at 8am? Simply open up your crontab, designate the execution parameters, and insert the execution command. The insertion would look like this:

* 8 * * * /usr/local/php/php /home/jason/timezone-email.php

This cron script specifies that at 8am daily the script timezone-mail.php should be passed to the PHP executable. Because the script calls for the output to be sent to my e-mail address, the data arrives almost immediately in my inbox. There’s nothing like coffee, donuts, and user resource statistics to start a morning….

Conclusion

The brilliant PHP contributors have done it once again, extending PHP’s capabilities in a manner that wasn’t expected, yet is now so enormously useful. In the next installment, I’ll expand upon this feature, introducing other aspects that you will want to keep in mind as you expand your PHP-based administration repertoire. As always, I welcome questions and comments. Please e-mail me at wj AT wjgilmore.com!

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is the Open Source Editorial Director for Apress (http://www.apress.com/). He’s the author of the upcoming book, PHP 5 and MySQL: Novice to Pro, due out by Apress in 2004. His work has been featured within many of the computing industry’s leading publications, including Linux Magazine, O’Reillynet, Devshed, Zend.com, and Webreview. Jason is also the author of A Programmer’s Introduction to PHP 4.0 (453pp., Apress). Along with colleague Jon Shoberg, he’s co-author of “Out in the Open,” a monthly column published within Linux magazine.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories