Menu

Command line scripting in PHP

PHP is a great language to develop web applications rapidly and economically. Like C, C++, Java, etc. PHP can also run as the command line. Many of us were unaware of this.

For eg., If you want to send emails to all subscribers in the email list. We cannot do this using a normal web script. However, we can do only it for sending emails to hundreds of subscribers. But it would be very difficult to send emails to thousands of email subscribers using web script.

Most of these tasks take some time to complete. By default, the maximum execution time would be 5 minutes. It can update in server settings. The execution time may vary from minutes to hours. Any web scripts have a few minutes to execute and are known as maximum execution time. After the maximum execution time, the web server will terminate the web script abnormally. 

Command-line scripts don't have a maximum execution time limit. These scripts can run as long as they want until the server shuts down or power failure. The time-consuming tasks like transferring the files from one server to another, backing up of the entire database, backing up of the entire website can be accomplished using the command-line interface.

Sample Command Line Script

A sample command line script to output "Hello World".

    <?php
        print "Hello World!";
    ?>

Filename: test_file.php

To run this: php test_file.php

Print built-in PHP Modules

    $ php -a

           Run PHP Interactively

    $ php -m

           calendar
           Core
           ctype
           curl
           date
           dom
           exif

Input/Output Streams        

The standard output streams defined in the CLI version of the PHP.

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

Example

    <?php
     fwrite(STDOUT, "Hello World!");
    ?>

We can use normal file functions like fopen(), fread(), fwrite to interact with the input/output streams.