PHP is a great language to develop web applications rapidly and economically. Many of us know this. But what many of us were unaware of is that PHP can also be run as a command-line script like C, C++, and Java, etc. Questions may arise why do we need to run PHP on the command line? After all, we just need to create websites with PHP, HTML, Graphics, and JavaScript.

Why PHP Command Line Scripting needed?

Apart from building web applications and websites, there are many other tasks that need to be run in the background in the webserver. Most of these kinds of tasks may take a few minutes to many hours to complete.

For example, sending a bulk newsletter email to all the subscribers in a mailing list. Can’t we do this in normal PHP through web scripting? Yes, we can do this through normal web scripting. However, this would work well only when there are a few hundreds of subscribers. What if there were a few thousands of subscribers? Usually, any web script would have only a few minutes to execute. This time period is known as maximum execution time. After which, the web server will terminate the web script abnormally.

By default, this maximum execution time would be set as 5 minutes and it may vary depending upon the server settings. In this case, our web script would be able to send only a few hundreds of emails within the given time limit. So is it not possible to develop a bulk email sending application in PHP? Yes, here comes the PHP Command Line Scripting.

Unlike web scripts, Command line scripts don’t have any maximum execution time limit and they can run as long as they can unless the server shuts down. Using command-line scripting, we can accomplish many time-consuming tasks like taking backup of entire websites and databases, transferring files to another server through FTP, and many more.

A Simple Command Line Script

How to write a command-line script in PHP? Will it be as easy as creating a web script? Yes, we can create a command-line PHP script as we do for web script, but with few little tweaks. We won’t be using any kind of HTML tags in command-line scripting, as the output is not going to be rendered in a web browser, but displayed in the DOS prompt / Shell prompt. Don’t ever try to use the <BR> tag for inserting a new line in the command line scripting ;). Instead, use \n to output the new line. Let us start with a small command-line script to output “Hello World”.

print "Hello World!";

Filename: helloworld.php

You can execute this script by typing the following in your command prompt or shell prompt:
php helloworld.php

Input / Output Streams

Instead of using print or echo for output, we can use the standard output stream defined in the CLI version of PHP. Following are the three IO streams in PHP with which we can interact the same way as we do with a file.

php://stdin (read)
php://stdout (write)
php://stderr (write)

These streams are defined as constants namely STDIN, STDOUT AND STDERR from PHP 4.3.0+ CLI version.

Now we rewrite the helloworld.php to use STDOUT.

fwrite(STDOUT, "Hello World!");

So these streams are treated as files and we can use normal file functions like fopen(), fread(), fwrite() to interact with these streams.
To get input from the end users, we can use STDIN with fgets(), fread(), fscanf() or fgetc().

For example, we would write a small script that gets the name of the user and output “Welcome <username>”.

fwrite(STDOUT, “Please enter your name\n”);
$name = fgets(STDIN);
fwrite(STDOUT, "Welcome $name");

The third stream STDERR is used to separate the error message from the normal output.
For example, the following script opens a file and read its contents and close the file. An error handler is also defined to write the errors to the STDERR stream.


function ErrorHandler($errno, $errstr, $errfile, $errline)
fwrite(STDERR,"$errstr in $errfile on $errline\n");

$fp = fopen("demo.txt","r");
$str = fread($fp,filesize("demo.txt"));
fwrite(STDOUT, "Task completed successfully!");

If the file “demo.txt” doesn’t exist, the following error messages will be displayed.

fopen(demo.txt): failed to open stream: No such file or directory in D:\demo\tmp\error.php on 10
filesize(): stat failed for demo.txt in D:\demo\tmp\error.php on 11
fread(): supplied argument is not a valid stream resource in D:\demo\tmp\error.php on 11
fclose(): supplied argument is not a valid stream resource in D:\demo\tmp\error.php on 12
Task completed successfully!

To avoid displaying errors to the end-user, we can pipe the output from the script as follows,

php error.php 2> error.log

Now, the user would see only the following message,

Task completed successfully!

The errors would be logged into a file named “error.log” in the directory where the script was executed. The number 2 is the command-line handle used to identify STDERR. Note that 1 handle for STDOUT. Using the > symbol from the command line, we can direct output to a particular location.

Finish Up

Now we have an idea of the basics of PHP Command Line Scripting. Though this article is a small introduction to PHP Command Line Scripting, hope it would have created a tiny spark for those who were unaware of Command-Line Scripting in PHP. Wishing these tiny sparks to be ignited to become a flame.