Aktuelle Seite: Code-Schnipsel » PHP » Arguments-Parser

Arguments-Parser

In PHP-Anwendungen für die Kommandozeile (CLI) ist es möglich, Befehlszeilenargumente wie für jedes andere Programm zu übergeben. Diese werden von PHP aber nicht ausgewertet, im Gegensatz zu den URL-Parametern auf Webseiten. Die hier vorgestellten Funktionen ermöglichen es, gezielt auf einzelne Parameter zuzugreifen und damit verbundene Werte abzufragen.

[o] Download (PHP-Datei, 3 kB)

[o] Quelltext-Ansicht: arguments.inc.php
<?php
// Command line arguments parser

// Known options definition: (where each "=" at the end denotes a following argument)
// $known_opts = array('a', 'b', 'c=');
// $known_longopts = array('aaa', 'bbb', 'ccc=');

$args = array();
$opts = array();

if (!isset($known_opts)) $known_opts = array();
if (!isset($known_longopts)) $known_longopts = array();

$process = true;
for ($i = 0; $i < $argc; $i++)
{
    $arg = $argv[$i];

    // This signals the end of any parameters
    if ($arg == '--')
    {
        $process = false;
    }

    // Check long options
    elseif ($process && substr($arg, 0, 2) == '--')
    {
        $ok = false;
        foreach ($known_longopts as $opt)
        {
            $add_args = 0;
            while (substr($opt, -1) == '=')
            {
                $add_args++;
                $opt = substr($opt, 0, -1);
            }

            if ($arg == '--' . $opt)
            {
                $this_opt = array($opt);
                while ($add_args--)
                {
                    $i++;
                    if (!isset($argv[$i])) die("Too few parameters for long option '$arg'\n");
                    $this_opt[] = $argv[$i];
                }
                $opts[] = $this_opt;
                $ok = true;
                break;
            }
        }
        if (!$ok)
        {
            die("Unrecognised long option '$arg'\n");
        }
    }

    // Check short options
    // Don't touch a '-' on its own, leave it as normal parameter
    elseif ($process && strlen($arg) > 1 && substr($arg, 0, 1) == '-')
    {
        // For each character
        for ($c = 1; $c < strlen($arg); $c++)
        {
            $ch = $arg{$c};
            $ok = false;

            foreach ($known_opts as $opt)
            {
                $add_args = 0;
                while (substr($opt, -1) == '=')
                {
                    $add_args++;
                    $opt = substr($opt, 0, -1);
                }

                if ($ch == $opt)
                {
                    $this_opt = array($opt);
                    while ($add_args--)
                    {
                        $i++;
                        if (!isset($argv[$i])) die("Too few parameters for option '-$ch'\n");
                        $this_opt[] = $argv[$i];
                    }
                    $opts[] = $this_opt;
                    $ok = true;
                    break;
                }
            }
            if (!$ok)
            {
                die("Unrecognised option '-$ch'\n");
            }
        }
    }

    // Non-options
    else
    {
        $args[] = $arg;
    }
}

// Find if an option is set
// Optionally checks a second name and combines with OR
//
function is_option_set($name, $name2 = null)
{
    global $opts;

    foreach ($opts as $opt)
    {
        if ($opt[0] == $name)
        {
            return true;
        }
        if ($name2 && $opt[0] == $name2)
        {
            return true;
        }
    }
    return false;
}

// Get the first option parameter for a given option name
// Only finds the first occurance of an option
// Optionally checks a second name
//
function get_option_value($name, $name2 = null)
{
    global $opts;

    foreach ($opts as $opt)
    {
        if ($opt[0] == $name)
        {
            return $opt[1];
        }
        if ($name2 && $opt[0] == $name2)
        {
            return $opt[1];
        }
    }
}

// Get the first option parameter for a given option name
// Finds all occurances of an option
// Optionally checks a second name
//
function get_all_option_values($name, $name2 = null)
{
    global $opts;

    $ret = array();
    foreach ($opts as $opt)
    {
        if ($opt[0] == $name)
        {
            $ret[] = $opt[1];
        }
        if ($name2 && $opt[0] == $name2)
        {
            $ret[] = $opt[1];
        }
    }
    return $ret;
}

// Get all option parameters for a given option name
// Only finds the first occurance of an option
// Optionally checks a second name
//
function get_option_all_values($name, $name2 = null)
{
    global $opts;

    foreach ($opts as $opt)
    {
        if ($opt[0] == $name)
        {
            return array_slice($opt, 1);
        }
        if ($name2 && $opt[0] == $name2)
        {
            return array_slice($opt, 1);
        }
    }
}

// Get the n-th argument
//
function get_argument($n)
{
    global $args;

    if (isset($args[$n])) return $args[$n];
    return '';
}

?>

Beispiel: Aufruf des Programms

./demoscript -c -i 12.34.56.78 --cert mydomain.crt mydomain.de

Beispiel: Verwendung im Programm

if ($argc < 1)
{
        echo "Your syntax description here.\n";
        echo "\n";
        echo "Usage:\n";
        echo "  demoscript [options] <domain> [<path>]\n";
        echo "\n";
        echo "Options:\n";
        echo "  -c, --cgi          Enable CGI execution on this domain\n";
        echo "  -s, --ssl          Enable SSL access to this domain\n";
        echo "  -i, --ip <num>     Bind this domain to a specific IP address\n";
        echo "      --cert <file>  Custom SSL certificate file suffix\n";
        echo "\n";
        echo "<domain> is the full domain name\n";
        echo "<path> is the document root subdirectory for this domain\n";
        exit();
}

$known_opts = array('c', 's', 'i=');
$known_longopts = array('cgi', 'ssl', 'ip=', 'cert=');

require('arguments.inc.php');

$cgi = is_option_set('c', 'cgi');
$ssl = is_option_set('s', 'ssl');
$ip = get_option_value('i', 'ip') or $ip = 0;
$certfile = get_option_value('cert');
$domain = get_argument(1);
$path = get_argument(2);

if ($domain == '') die("No domain name specified.\n");

Lizenz, Nutzungsbedingungen

Dieses Programm ist als kompilierte Version und im Quelltext frei und uneingeschränkt verfügbar („Public Domain“). Ich gebe keine Garantie, auch nicht auf Lauffähigkeit oder Benutzbarkeit. Die Nutzung erfolgt auf eigene Gefahr, ich hafte nicht für Schäden, die durch sachgemäßen oder unsachgemäßen Gebrauch dieses Programms entstehen.

Ausblenden
Statistik wird geladen...