php
This subchapter looks at php, a UNIX (and Linux) command, including both running shell scripts from a web browser and running PHP from the shell.
php is used to run a CLI version of PHP.
php script example
This example assumes that you have created the scripts directory in your home directory.
Create a php script called script.php and save it in the new scripts directory (folder):
<?php
echo "Hello World!"
?>
Notice that we skip the chmod step typical for activating shell scripts.
Run your new script by running the php program with your script as the file to execute:
$ php ~/scripts/script.php
Hello World!
$
Note that the shell does not render HTML, so if you run a web scirpt, you will see raw HTML, CSS, and JavaScript as plain text in your terminal window.
You can run perl, ruby, and python scripts in the same manner.
running shell from PHP
You can run shell commands and shell scripts from PHP in Apache by using either the shell_exec function or backticks.
The shell_exec function in PHP takes a shell command as a string, runs that command (or command list) in shell, and returns the rsult as a string. You can assign the result to a string variable and then output those results to a web browser, with or without additional processing. Use the <pre> tag to have the browser use the UNIX new line characters.
<php
$linesofoutput = shell_exec('ls');
echo '<pre>'.$linseofoutput.'</pre>';
?>
You can also use the backtick (or back quote) character (`).
<php
$linesofoutput = `ls`;
echo '<pre>'.$linseofoutput.'</pre>';
?>
You cannot combine both methods. This is useful, because you might actually want to send the backticks to the shell. If you are using backticks to run a shell command or command list, you can escape internal backticks to send them to the shell.
web security
Most system administrators disable shell_exec(). When shell_exec is disbled, the PHP script will be unable to run any shell commands.
If you enable shell access, you must guarantee that web visitor submitted input is never sent to the command shell without thorough scrubbing or crackers will be able to take over your server.
The difficulty with that guarantee is that there is probably a lot of PHP you didnt write, such as WordPress, a PEAR package, off-the-shelf software, etc.
Hence the rule: disable shell_exec() and similar functions for any public facing server. Thanks to Stuart Beeton for emphasizing this point.
command line PHP
PHP is available both as a CGI binary (for Apache) and a CLI binary (for the shell).
Use the -v option to find out how your CLI copy of PHP is set up.
$ php -v
PHP 5.3.15 with Suhosin-Patch (cli) (built: Jul 31 2012 14:49:18)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
$
Notice that the above output indicated the cli version.
PHP defaults
The CLI version of PHP does not send out any HTTP headers, because the shell doesnt understand them and instead expects plain text.
The CLI version of PHP does not change the working directory to that of the script. For a web server, you want to find all the files from the current web base. For a script running in the shel, you want the script or operator to make the decision. This allows a PHP script running in the shell to be generic and simply run in the current working directory.
The CLI version of PHP has several php.ini options overridden by default. These changes are enforced after the php.ini file is run, so you cant change them in the configuration file, although you can change them during runtime.
- html_errors is FALSE(because the shell is cluttered by uninterpretted HTML tags.
- implicit_flush is TRUE because the shell should receive immediate outputs of print, echo, and similar commands rather than having them held in a buffer.
- max_execution_time is 0 (unlimited) because a shell environment might run very much more complex scripts than those in a typical web-based script.
- register_argc_argc is TRUE because the PHP script will need to process the command line arguments. The PHP variable $argc has the number of arguments passed and the variable $argv is an array of the actual arguments. These values are also in the $_SERVER array, as $_SERVER['argv'] and $_SERVER['argc'].
- output_buffering is hardcoded FALSE< but the output buffering functions are available.
- max_input_time is FALSE because PHP CLI does not support GET, POST, or file uploads.
running a file in PHP
Use the -f option to parse and execute a designated file in PHP.
$ php -f filename.php
$
Note that the -f switch is optional. You will get the same result if you leave off the -f option and just give the filename. You get the exact same results from:
$ php filename.php
$
Note that the .php extension is for your convenience.The CLI PHP will run any file as if it were a PHP file, without regard to the extension type.
run PHP interactively
Use the -a switch to run PHP interactively. You will receive a secondary prompt and each line of PHP code will be run as soon as a ; or } is found. Do not include the script tags <? and ?>.
$ php -a
asdf
$
run single line of PHP
Use the -r switch to run some particular PHP code immediately. This is useful inside of a script. Do not include the script tags <? and ?>.
$ php -r 'echo 'hello world\n'
hello world
$
You need to carefully watch your use of quoting and escaping to avoid problems with the command line variable substitution done by the shell.
syntax check
Use the -l switch to perform a syntax check on the PHP code.
$ php filename
No syntax error detected in <filename>
$
If there are no errors, you will get the message No syntax errors detected in <filename > on standard output and the shell return code is 0.
If there are no errors, you will get the message Errors parsing <filename > on standard output and the shell return code is -1.
This option does not work with the -r option.
use PHP in a pipeline
PHP will accept PHP code from standard input (STDIN). Note this means that the previous commands are creating PHP code, not passing data for a PHP file to use as input.
$ some_application | some_filter | php | some_command > final_output.txt
$
combinations
You cannot combine any of the three ways of executing PHP code (file, -r, and STDIN). It would be great if there was a way to accept data from STDIN and name a PHP file to process it, with the output continuing as STDOUT to the next commadn in the shell pipeline, but this isnt currently a choice.
arguments
PHP can receive an unlimited number of arguments. Unfortunately, the shell has a limit on the number of total characters which can be passed to a command.
An argument that starts with a - will be used by the PHP interpreter. Use the argument list separator -- and all of the arguments that follow will be sent to the PHP script through the $argv variable.
shebang
You can insert the shebang line with the correct location of the CLI PHP program and set the execution attrbutes of the file. The file needs the normal PHP starting and end tags.
Use the type command to find the location of your CLI copy of PHP.
$ type php
php is /usr/bin/php
$
Add that location to the standard shebang as the first line of the file.
#!/usr/bin/php
Set the file to execute:
$ chmod +x filename.php
$
The shebang line has no effect on Windows, but also causes no harm because it is also a valid PHP comment. Therefore include the shebang line for true cross-platform PHP scripts.
shebang example
Create a sample script file.
#!/usr/bin/php
<?php
var_dump($argv);
?>
Make the script file excutable and then run it.
$ chmod +x phptest.php
$ ./phptest.php -h -- foo
array(4) {
[0]=>
string(13) "./phptest.php"
[1]=>
string(2) "-h"
[2]=>
string(2) "--"
[3]=>
string(3) "foo"
}
$
comments, suggestions, corrections, criticisms
free music player coding example
Coding example: I am making heavily documented and explained open source code for a method to play music for free almost any song, no subscription fees, no download costs, no advertisements, all completely legal. This is done by building a front-end to YouTube (which checks the copyright permissions for you).
View music player in action: www.musicinpublic.com/.
Create your own copy from the original source code/ (presented for learning programming).
Because I no longer have the computer and software to make PDFs, the book is available as an HTML file, which you can convert into a PDF.
Names and logos of various OSs are trademarks of their respective owners.