You're here: Home / PHP /

How to Read Command Line Arguments from Your Script

Writing scripts that run from command line is sometimes useful. It gives us more flexibility rather than scripts that called from web browsers. But passing parameters to these scripts is a little different. They don't recognize GET and POST variables, so you can't pass GET and POST variables to these script.

The good news, reading command line arguments is very easy! Let's see an example. Suppose you are writing an image downloader script that takes four arguments: the website, the file type to download, the username and pasword to login to the site. You run the script by calling it from command line like this:

php imgdownloader.php -U http://www.bikini.com/todaypics.html -u u4523 -p secret -t jpg

The command above will tell your script login to http://www.bikini.com as user u4523 and supply secret for the password, then download all jpeg images from todaypics.html. Here's how to read the arguments from your script:

<?php
$url      = '';
$username = '';
$password = '';
$filetype = '';

while(count($argv) > 0) {
    $arg = array_shift($argv);
    switch($arg) {
        case '-U':
            $url  = array_shift($argv);
            break;
        case '-u':
            $username = array_shift($argv);
            break;
        case '-p':
            $password = array_shift($argv);
            break;
        case '-t':
            $filetype = array_shift($argv);
            break;
    }
}

/* print them */
print "URL:      $url\n";
print "username: $username\n";
print "password: $password\n";
print "filetype: $filetype\n";

/* will print: */
/*
URL:      http://www.bikini.com/todaypics.html
username: u4523
password: secret
filetype: jpg
*/
?>

Keywords: command line arguments, reading, parsing, php, php-cli

Share:  del.icio.us logo Save to del.icio.us  digg logo Digg this!

comment.gifAdd your comment

(required, will not be published) (optional)