Chapter 25. Command-Line PHP
Introduction
PHP was created for web programming and is still used mostly for that purpose. However, PHP is also capable as a general-purpose scripting language. Using PHP for scripts you run from the command line is especially helpful when they share code with your web applications. If you have a discussion board on your web site, you might want to run a program every few minutes or hours to scan new postings and alert you to any messages that contain certain keywords. Writing this scanning program in PHP lets you share relevant discussion-board code with the main discussion-board application. Not only does this save you time, but also helps avoid maintenance overhead down the road.
Beginning with version 4.3, PHP builds include a command-line interface (CLI) version. The CLI binary is
similar to web server modules and the CGI binary but has some important
differences that make it more shell friendly. Some configuration
directives have hardcoded values with CLI; for example, the html_errors directive is set to false, and implicit_flush is set to true. The max_execution_time directive is set to 0,
allowing unlimited program runtime. Finally, register_argc_argv is set to true. This means you can look for argument
information in $argv and $argc instead of in $_SERVER['argv'] and $_SERVER['argc']. Argument processing is
discussed in Recipes 25.1 and 25.2.
To run a script, pass the script filename as an argument:
% php scan-discussions.php
On Unix, you can also ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access