Using PHP for Command-Line Scripts
PHP scripts don’t need to be run from a web server—although that’s how the majority of PHP scripts are deployed. In this section, we’ll briefly look at how you can run PHP scripts from the command line. This allows you to query the MySQL server from the command line to generate reports and to import or export data.
Consider Example 14-5, which simply says “Hello, world!”.
Example 14-5. A PHP script to say hello
<?php echo "Hello, world\n"; ?>
Type this in an editor and save it to a file called hello.cl.php.
You can run PHP scripts from the shell prompt or command window by running the PHP executable and passing the name of the script to it:
$php hello.cl.phpHello, world
If the operating system can’t find the php executable, you’ll need to specify the
full path to the file. On a Linux or Mac OS X system, this may be
available as the file /usr/bin/php. If you’ve installed XAMPP,
you can use the program /opt/lampp/bin/php on Linux, /Applications/xampp/xamppfiles/bin/php on
Mac OS X, and C:\Program
Files\xampp\php\php.exe on Windows.
You can also have the operating system call the PHP program automatically when you run a PHP script from the command line. To do this on a Linux or Mac OS X system, you need to add this line to the top of each script to specify the PHP program to use:
#!path_to_the_php_executableFor example, you could specify the /usr/bin/php program in the hello.cl.pl script as follows:
#!/usr/bin/php <?php echo "Hello, world\n"; ?>
You ...
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