Chapter 19. Command-Line PHP

Usually, the PHP engine is invoked by a web server in response to a request from a web client. However, the PHP engine can also be run as a command-line utility on your computer. If you’ve been running all of the code examples in the book so far, you’ve run PHP as a command-line program when you used PHPUnit and Composer.

Writing a PHP program intended for use on the command line is a little different than writing a PHP program intended for use in a website. You have access to all the same functions for string manipulation, JSON and XML handling, working with files, and so forth, but there’s no incoming form or URL data. Instead, you get information from command-line arguments. The standard print statement prints data to the console. The next section, “Writing Command-Line PHP Programs”, shows you the basics of writing a command-line PHP program.

The PHP engine also comes with a mini web server that you can invoke by running PHP on the command line. “Using PHP’s Built-in Web Server” explains how this works. The built-in web server is handy for quick testing.

One other handy use for PHP on the command line is as an interactive shell, otherwise known as a Read-Eval-Print Loop (REPL). This is a program that gives you a prompt to type in some PHP code, and then runs that PHP code and tells you the results. For exploration of how a PHP function works and quick gratification, nothing beats a REPL. “Running a PHP REPL” explains PHP’s ...

Get Learning PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.