Read input and manipulate files on Linux systems with PHP scripts

If you are already familiar with PHP code for Web sites, then you'll find it works great for command-line scripting on Linux systems.

Gone are the days when Perl was the first-choice interpreted language for command-line scripting on Linux systems. These days, a number of choices are available, including Python, Ruby, and PHP. If you already write PHP code for Web sites and are familiar with the language, using PHP on the command-line works fantastic and fast.

Perhaps one of the biggest functions of any scripting language in a script is to manipulate files and obtain user input. PHP handles this with as much grace as any other scripting language.

For instance, to have PHP handle reading user-supplied input during script execution, use:

function read_input()
    $fp    = fopen("/dev/stdin", "r");
    $input = trim(fgets($fp, 255));
    return $input;
printf("Please supply your name: ");
$name = read_input();
printf("\nHello, $name.\n");

The read_input() function defined above will take input from STDIN, store it in the $input variable, trim all leading and trailing white space, and return it.

The same principle can be used to read and manipulate standard files; remember that to Linux STDIN is just another file (hence opening /dev/stdin in the above example).

if (file_exists($argv[1]))
    $file = $argv[1];
} else {
    printf("ERROR: File '$file' does not exist!\n");
    exit 1;
$data = file($file);
$c    = 1;
foreach ($data as $line)
    printf(sprintf("[%s]: %s", $c, $line));

In the above example, the PHP script will read every line from the file passed on the command line and output it with the current line number preceding it. If the file does not exist, the script will print an error and exit with a return code of 1 (signifying an error; on a normal operation, the script would exit with a return code of 0). The file() function is used here as it reads every line of the file into an array (in this case, $data), which is then used in the foreach() statement to loop through the array, once per line in the file.

PHP is no longer strictly for Web-based programming. It can be used quite easily for command-line scripting and is both flexible and fast. Likewise, nearly everything you can do with a Web script, such as database manipulation, can be done with a command-line script in PHP just as easily.

Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!