I've small php script in my public folder called sample.php. I run this file using drush command drush scr sample.php.
I want to know how to pass argument to php file using drush command and how to get arguments in php file?
This is explained quite nicely in drush topic scripts
.
Your script should start with:
#!/usr/bin/env drush
<?php
Then, you may call your script directly. For example, if you have saved your script in a file called myscript
, then you would call it via:
$ myscript a b --flag=bar
Drush provides a method called drush_shift
that allows you to access you one at a time:
$first = drush_shift();
$second = drush_shift();
In the above example, $first
will be a
and $second
will be b
. You may access your options via drush_get_option()
as usual.
$flag = drush_get_option('flag');
$other = drush_get_option('other', 'default');
In the above example, $flag
is bar
and other
is `$default'.
Note that you can use $argv
as suggested in the other answer, but if you do this, your arguments and options will be mixed together, and you will need to parse them yourself. Using drush_shift()
and drush_get_option();
is more convenient.
drush_shift()
and drush_get_option()
also works without making the script directly executable. Perhaps the answer should reflect that as well by marking the relevant part as optional.
Commented
Feb 7, 2019 at 12:51
On Drush 10, I managed to work with:
<?php
$first = $extra[0];
$second = $extra[1];
Calling script with
./vendor/bin/drush php:script scripts/my-script.php -- firstarg secondarg
Posible Solucion:
$_SERVER['argv'][3]
Comand:
drush scr 'testScript.php' field
Now, $_SERVER['argv'][3] = field
Enjoy!
In php command line you can use pass arguments to your script and inside your script grab it by using $argv variable:
check this out: http://php.net/manual/en/reserved.variables.argv.php
drush scr path/to/script --id=15
. And then if your script starts with #!/usr/bin/env drush
(as @greg_1_anderson mentioned) than you can get your parameter via $id = drush_get_option('id');
inside this script.
Commented
Sep 16, 2016 at 13:38
You can use an environment variable:
MY_FLAG=value drush do_something
In php you can then retrieve this variable:
echo $_SERVER['MY_FLAG'];