The days of Perl as the preferred interpreter for Linux system command line scripting are gone forever. Today, we have more choices, including Python, Ruby, and PHP. If you've already written PHP code for your site and you know the language well, you'll find it amazing how fast you can use PHP at the command line.
One of the biggest uses of any scripting language in a script is to manipulate files and get user input. PHP handles these in no way inferior to any other scripting language.
For example, use PHP to process read user input during script execution, using:
#!/usr/bin/php
<?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 ("Hello, $name.");
?>
</code>
The Read_input () function defined above is extracted from stdin, stored in the $input variable, and all boot and trailing blank spaces are sorted and returned.
The same principle can also be applied to reading and manipulating standard files; Remember, for Linux,stdin is just another file (and, correspondingly, Opening/dev/stdin in the example above).
#!/usr/bin/php
<?php
if (File_exists ($argv [1]))
{
$file = $argv [1];
} else {
printf ("Error:file ' $file ' does not exist!");
Exit 1;
}
$data = file ($file);
$c = 1;
foreach ($data as $line)
{
printf (sprintf ("[%s]:%s", $c, $line));
$c + +;
}
In the example above, the PHP script will read each row passed to the command line file and output it immediately following the current number of rows. If the file does not exist, the script prints an error message and returns code 1 and Exits (1 indicates an error; In normal operation, the script exits with a return code of 0). The file () function is used here to read each row of the file, in the array (in this case, the array is $data), and then in the foreach () statement, looping through the array, one line in the file.
PHP is no longer rigidly wedded to web-based programming. We can easily apply it to writing command-line scripts, both flexible and fast.
Similarly, almost all of the things you can do with Web scripts, such as database operations, can be easily applied to PHP's command line scripts.