Skip to content

Instantly share code, notes, and snippets.

@rickdaalhuizen90
Created January 28, 2018 16:40
Show Gist options
  • Save rickdaalhuizen90/6430f7f4ef01e14eabb457fa64efac3b to your computer and use it in GitHub Desktop.
Save rickdaalhuizen90/6430f7f4ef01e14eabb457fa64efac3b to your computer and use it in GitHub Desktop.
Example of parsing arguments in php cli
Example:
php -s "Hello world" -h md5
php --string "Hello world" --hash md5
<?php
class Hash
{
protected $string;
protected $hash;
/**
* Init arguments
* @param array $argv cli arguments
*/
public function __construct(array $argv)
{
$this->parseArgs($argv);
}
/**
* Parse arguments
* @param array $argv cli arguments
* @return void exit if arguments are null
*/
protected function parseArgs(array $argv)
{
array_shift($argv); // Remove argv[0] from the arguments
$short_opts = 's:h:';
$long_opts = array('string:', 'hash:');
$options = getopt($short_opts, $long_opts);
foreach(array_keys($options) as $key){
if ($key === 's' || $key === 'string')
$this->string = is_array($options[$key]) ? $options[$key][0] : $options[$key];
if ($key === 'h' || $key === 'hash')
$this->hash = is_array($options[$key]) ? $options[$key][0] : $options[$key];
}
if (is_null($this->string) || is_null($this->key)) {
echo 'Missing arguments';
die;
}
}
/**
* Hash string to md5 or sha1
* @return string return hashed string
*/
public function run()
{
switch ($this->hash) {
case 'md5':
print md5($this->string);
break;
case 'sha1':
print sha1($this->string);
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment