How to Read Command Line Arguments from Your Script

Nov 7, 2008 | Tags: PHP | del.icio.us del.icio.us | digg Digg

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:

Listing 1: imgdownloader.php

  1. <?php
  2. $url      = '';
  3. $username = '';
  4. $password = '';
  5. $filetype = '';
  6.  
  7. while(count($argv) > 0) {
  8.     $arg = array_shift($argv);
  9.     switch($arg) {
  10.         case '-U':
  11.             $url  = array_shift($argv);
  12.             break;
  13.         case '-u':
  14.             $username = array_shift($argv);
  15.             break;
  16.         case '-p':
  17.             $password = array_shift($argv);
  18.             break;
  19.         case '-t':
  20.             $filetype = array_shift($argv);
  21.             break;
  22.     }
  23. }
  24.  
  25. /* print them */
  26. print "URL:      $url\n";
  27. print "username: $username\n";
  28. print "password: $password\n";
  29. print "filetype: $filetype\n";
  30.  
  31. /* will print: */
  32. /*
  33. URL:      http://www.bikini.com/todaypics.html
  34. username: u4523
  35. password: secret
  36. filetype: jpg
  37. */
  38. ?>

Related Articles

Leave a comment

Name (required)
Email (will not be published) (required)
Website

Characters left = 1000

Tags

Recent Posts

  1. OpenCV Utility: Reading Image Pixels Value
  2. OpenCV Circular ROI
  3. OpenCV 2.0 Installation on Windows XP and Visual Studio 2008
  4. Runtime ROI Selection using Mouse
  5. Real Time Eye Tracking and Blink Detection
View Archives

About the Author

avatar Cool PHP programmer writing cool PHP scripts. Feel free to contact
Tel. +62 31 8662872
+62 856 338 6017
ICQ 489571630
Skype dede_bl4ckheart
Yahoo dede_bl4ckheart
Google nashruddin.amin

Recommended Sites:

Hacker's HTTP Client
HTML and CSS Tutorials
Stop Dreaming Start Action
Online Quran and Translation