PHP
  Home arrow PHP arrow Page 4 - Implementing with PHP: Standalone Scripts
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Implementing with PHP: Standalone Scripts
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2006-08-31


    Table of Contents:
  • Implementing with PHP: Standalone Scripts
  • Introduction to the PHP Command-Line Interface (CLI)
  • Handling Input/Output (I/O)
  • Parsing Command-Line Arguments

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Implementing with PHP: Standalone Scripts - Parsing Command-Line Arguments
    ( Page 4 of 4 )

    When you are running a PHP script on the command line, you obviously can't pass arguments via $_GET and $_POST variables (the CLI has no concept of these Web protocols). Instead, you pass in arguments on the command line. Command-line arguments can be read in raw from the $argv autoglobal.

    The following script:

    #!/usr/bin/env php
    <?php
     print_r($argv);
    ?>

    when run as this:

    > ./dump_argv.php foo bar barbara

    gives the following output:

    Array
    (
      [0] => dump_argv.php
      [1] => foo
      [2] => bar
      [3] => barbara
    )

    Notice that $argv[0] is the name of the running script.

    Taking configuration directly from $argv can be frustrating because it requires you to put your options in a specific order. A more robust option than parsing options by hand is to use PEAR's Console_Getopt package. Console_Getopt provides an easy interface to use to break up command-line options into an easy-to-manage array. In addition to simple parsing, Console_Getopt handles both long and short options and provides basic validation to ensure that the options passed are in the correct format.

    Console_Getopt works by being given format strings for the arguments you expect. Two forms of options can be passed: short options and long options.

    Short options are single-letter options with optional data. The format specifier for the short options is a string of allowed tokens. Option letters can be followed with a single : to indicate that the option requires a parameter or with a double :: to indicate that the parameter is optional.

    Long options are an array of full-word options (for example, --help).The option strings can be followed by a single = to indicate that the option takes a parameter or by a double == if the parameter is optional.

    For example, for a script to accept the -h and --help flags with no options, and for the --file option with a mandatory parameter, you would use the following code:

    require_once "Console/Getopt.php";
    
    $shortoptions = "h";
    $longoptons = array("file=", "help");
    
    $con = new Console_Getopt;
    $args = Console_Getopt::readPHPArgv();
    $ret = $con->getopt($args, $shortoptions,
    $longoptions);

    The return value of getopt() is an array containing a two-dimensional array. The first inner array contains the short option arguments, and the second contains the long option arguments. Console_Getopt::readPHPARGV() is a cross-configuration way of bringing in $argv (for instance, if you have register_argc_argv set to off in your php.ini file).

    I find the normal output of getopt() to be a bit obtuse. I prefer to have my options presented as a single associative array of key/value pairs, with the option symbol as the key and the option value as the array value. The following block of code uses Console_Getopt to achieve this effect:

    function getOptions($default_opt, $shortoptions,
    $longoptions) { require_once "Console/Getopt.php"; $con = new Console_Getopt; $args = Console_Getopt::readPHPArgv(); $ret = $con->getopt($args, $shortoptions,
    $longoptions); $opts = array(); foreach($ret[0] as $arr) { $rhs = ($arr[1] !== null)?$arr[1]:true; if(array_key_exists($arr[0], $opts)) { if(is_array($opts[$arr[0]])) { $opts[$arr[0]][] = $rhs; } else { $opts[$arr[0]] = array($opts[$arr[0]], $rhs); } } else { $opts[$arr[0]] = $rhs; } } if(is_array($default_opt)) { foreach ($default_opt as $k => $v) { if(!array_key_exists($k, $opts)) { $opts[$k] = $v; } } } return $opts; }

    If an argument flag is passed multiple times, the value for that flag will be an array of all the values set, and if a flag is passed without an argument, it is assigned the Boolean value true. Note that this function also accepts a default parameter list that will be used if no other options match.

    Using this function, you can recast the help example as follows:

    $shortoptions = "h";
    $longoptions = array("file=", "help");
    
    $ret = getOptions(null, $shortoptions,
    $longoptions);

    If this is run with the parameters -h --file=error.log, $ret will have the following structure:

    Array
    (
      [h] => 1
      [--file] => error.log
    )

    Please check back next week for the continuation of this article.



     
     
    >>> More PHP Articles          >>> More By Sams Publishing
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    Stay green...Green IT