Tuesday, March 5, 2013

PHP getopt alternative

Are you using getopt. It works but if you are stuck in legacy version of PHP you will miss long options. And what if you do not wan't to use '-' as separator. We could use the idea from Bash and array_shift parameters. See the sample bellow.

<?php
function DisplayHelp () {
  echo "Usage:\n";
  echo "     -f, --folder folder to produce output to  \n";
  echo "     -s, --server ftp server to use \n";
  echo "     -u, --user ftp server user  \n";
  echo "     -p, --pass ftp server password  \n";
  echo "     --port ftp server port, defaults to 21  \n";
  echo "     -d, --debug debug mode \n";
  echo "     -l, --log location";
  echo "     -h, --help display this help and exit";
  echo "\n";
  exit();
}

$options = array();

if (!(php_sapi_name() == 'cli')) {
  echo 'You need to run this from console.';
  exit();
}

//remove the name of the executing script
array_shift($argv);

//no options chosen
if (!is_array($argv))
  DisplayHelp();

//parse parameters
while (($param = array_shift($argv)) !== NULL) {
  switch ($param) {
    case '--folder':
    case '-f':
      $options['folder'] = array_shift($argv);
      break;
    case '--server':
    case '-s':
      $options['server'] = array_shift($argv);
      break;
    case '--user':
    case '-u':
      $options['user'] = array_shift($argv);
      break;
    case '--pass':
    case '-p':
      $options['pass'] = array_shift($argv);
      break;
    case '--port':
      $options['port'] = array_shift($argv);
      break;
    case '--debug':
    case '-d':
      $options['debug'] = TRUE;
      break;
    case '--log':
    case '-l':
      $options['log'] = array_shift($argv);
      break;
    case '--help':
    case '-h':
      DisplayHelp();
      break;
    default:
      DisplayHelp();
      break;
  }
}

//show options
print_r($options)
?>
Post a Comment