When developing on a local machine, sometimes it makes sense to create scripts used as tools run via the command line. This can even be useful if you’re a PHP developer, and like to develop PHP scripts for other purposes than web-development. Since PHP has access to your files system, you can easily program PHP scripts to do something on your system, manually of by cron-job, especially if you’re on a Unix computer.
It’s important to notice that some environment-specific things change, when working with the command line, rather than a web server. E.g. there are no GET or POST parameters etc., but instead you can work with arguments passed to the script when you execute it.
Check if the scripts is run via command line
php_sapi_name(); // returns "cli" if script is run via command line
Default PHP command line arguments
// Run command line script php MyScript.php foo bar // The $argv variable contains the arguments run, including the script name $argv = array( 'MyScript.php', 'foo', 'bar', );
Sophisticated command line arguments, emulating POST/GET parameters
// Run command line script php MyScript.php arg1=foo arg2=bar // Convert arguments to key/value pairs, like the $_GET or $_POST arrays $args = array(); foreach ($argv as $arg) { if ($pos = strpos($arg,'=')) { $key = substr($arg,0,$pos); $value = substr($arg,$pos+1); $args[$key] = $value; } } // Parsed arguments $args = array( 'arg1' => 'foo', 'arg2' => 'bar', );
Have fun coding :-)
No comments yet (leave a comment)