Gone are the days when Perl was the preferred interpreted language for command line scripts on Linux systems. Today, we have more choices, including Python, Ruby, and PHP. If you have already written PHP code for your website and are familiar with this language, then you will find that using PHP on the command line is surprisingly fast and the effect is amazing.
In scripts, one of the biggest functions of any scripting language is to operate files and obtain user input. PHP handles these no less well than any other scripting language.
For example, to use PHP to handle reading user-supplied input during script execution, use:
#!/usr/bin/php
function read_input( )
{
$fp = fopen("/dev/stdin", "r");
$input = trim(fgets($fp, 255));
fclose($fp) ;
return $input;
}
printf("Please supply your name: ");
$name = read_input();
printf("nHello, $name. n");
?>
The read_input() function defined above will extract the input from STDIN and store it in the $input variable, sorting out all leading and trailing of empty space and then returns.
The same principle can be applied to reading and manipulating standard files; remember that to Linux, STDIN is just another file (correspondingly, the same is true for opening /dev/stdin in the above example).
#!/usr/bin/php
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)) ;
$c ;
}
In the above example, the PHP script will read each line passed to the command line file and output it immediately following the current line number. If the file does not exist, the script will print an error message and exit with return code 1 (1 indicates an error; during normal operation, the script will exit with return code 0). The file() function is used here, it reads each line of the file into an array (in this example, the array is $data), and then is used in a foreach() statement to loop through the array, one at a time in the file One line.
PHP is no longer strictly limited to web-based programming. We can easily apply it to writing command line scripts, which is both flexible and fast. Likewise, almost everything you can do with Web scripts, such as database operations, can be easily done using PHP command-line scripts.