PHP shebangPosted in PHP -
I've posted a number of times in the past about how it is possible to run PHP scripts from the command line and here dedicate a post to showing how a PHP script can be run by adding a shebang line and running it as if it were any other command.
What's a shebang line?
A shebang line (which is also known as a hashbang, hashpling, pound bang, or crunchbang) is the first line of a text script which tells *nix operating systems which interpreter to use to run the script.
The shebang line starts with #! and then includes the full path and command of the interpreter to run the script. For example a bash script would start with #!/bin/bash
Using a shebang line with PHP
First you need to know the path to the PHP interpreter. On Debian and CentOS it's /usr/bin/php but it may be different on other distributions. Try "which php" from the command line to find where it is.
Now add this to the first line of your PHP script like so, followed by <?php to start the PHP script and then the rest of your code:
#!/usr/bin/php <?php // your PHP code here
The PHP script needs to be executable by the user who is running it. If the script is at /home/me/myscript.php and you only want yourself to be able to read, write and execute it then chmod 0700 like so:
chmod 0700 /home/me/myscript.php
Check the chmod page at Wikipedia for more details and other permission examples.
Running the script
Now that the shebang line has been added and the script has been made executable, it's possible to just call the script from the command line, either with a relative path, an absolute path, or a ./ path if you are in the same directory as the script. Alternatively, if the script is in your $PATH it can be executed just with the script name.
/home/me/myscript.php ../myscript.php ./myscript.php myscript.php
The first example above is an absolute path; then a relative path; then if the script is in the current working directory; and finally if it's in the $PATH (not normally recommended).
Alternatively, you can not make it executable and execute by calling the PHP executable and passing the script name as a parameter:
I usually prefer the latter method but it is useful to be able to do it either way.