Perl is the preferred language for interpreting Linux Command Line scripts. Today, we have more options, including Python, Ruby, and PHP. If you have already compiled PHP code for your website and are familiar with this language, you will find that using PHP on the command line is fast and the effect is amazing.
In scripts, one of the biggest functions of any scripting language is to operate on files and obtain user input. PHP is no inferior to any other scripting language.
For example, when using PHP to process and read user input during script execution, use:
#! /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 ("nHello, $ name. n ");
?>
</Code>
The read_input () function defined above extracts input from STDIN, stores it in the $ input variable, sorts all leading and trailing blank spaces, and then returns.
The same principle can also be applied to reading and operating standard files. Remember, for Linux, STDIN is just another file (correspondingly, the opening/dev/stdin in the above example also works ).
#! /Usr/bin/php
<? 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 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 will print an error prompt, return code 1 and exit (1 indicates an error; in normal operation, the script will exit with return code 0 ). The file () function is used here. It reads each row of the file and columns it into an array (in this example, the array is $ data). Then, it is used in the foreach () statement, loop in the array, one is a row in the file.
PHP is no longer strictly tied to Web-based programming. We can easily use it to write command line scripts, which is flexible and fast. Similarly, almost all operations that you can perform with Web scripts, such as database operations, can be easily completed using PHP Command Line scripts.