tags:

views:

289

answers:

2

This question is regarding getopt function in php. I need to pass two parameter to the php scripts like

php script.php -f filename -t filetype

Now depending upon the file type which can be u, c or s I need to do proper operation.

I am using switch case for the same:

Here is the Code I am using:

// Get filename of input file when executing through command line.
$file = getopt("f:t:");

Switch case should compare the type of the file which I am passing in from the command line (u, c or i) and accordingly match it and do the operation.

switch("I am not sure what should go in there and this is wrong,Please advice")
    {

        case `Not sure`:
            $p->ini();
            break;

        case `Not sure`:
            $p->iniCon();
            break;

        case `Not sure`:
            $p->iniImp();
            break;
    }

Kindly advise on this !!!

+2  A: 

If you just put something like this in your PHP script (called, on my machine, temp.php) :

<?php
$file = getopt("f:t:");
var_dump($file);

And call it from the command-line, passing those two parameters :

php temp.php -f filename -t filetype

You'll get this kind of output :

array(2) {
  ["f"]=>
  string(8) "filename"
  ["t"]=>
  string(8) "filetype"
}

Which means that :

  • $file['f'] contains the value passed for -f
  • and $file['t'] contains the value passed for -t


Starting from there, if you want your switch to depend on the option passed as the value of -t, you'll use something like this :

switch ($file['t']) {
    case 'u':
            // ...
        break;
    case 'c':
            // ...
        break;
    case 'i':
            // ...
        break;
}

Basically, you put :

  • The variable that you want to test in the switch()
  • And the possible values in the cases


And, for more informations, you can read, in the PHP manual :

Pascal MARTIN
Thanks alot Pascal for the information and help.
Rachel
A: 

There is a problem in your approach. What if user gives following command line by mistake. the script will not be able to detect it and fail as $file['t'] will be an array.

php temp.php -f filename -t filetype -f filename2

Mohit