Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Use command-line PHP arguments

Thursday, March 21st, 2013 by Servage

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(

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 :-)

Use command-line PHP arguments, 4.5 out of 5 based on 2 ratings
Categories: Guides & Tutorials, Tips & Tricks


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.