|
Like with a php driven website it's easy to pass variables to your php standalone script.
However, there is a difference because by default a standalone script takes only single arguments separated by a whitespace. So, calling ./variables.php?action=start&town=nowhere
will not work. Your shell would look for an executable script of exactly this name, "./variables.php?action=start&town=nowhere". This doesn't exist of course.
Instead you have to pass only the values like this: ./variables.php start nowhere
This values will then be available in the $argv - array.
variables.php
#1: <?
would give you
Array
(
[0] => variables.php
[1] => start
[2] => nowhere
)
Note that the first element of $argv is always the script name itself.
This, however, will not allow you to reference your values by name and you will have to be very careful to have them always in the right order.
A better alternative is the use of the getopt() function:
getopt.php
#1: <?
You can call this script like this:
php getopt.php -a start -t nowhere
which will give you
Array
(
[a] => start
[t] => nowhere
)
Better, isn't it?But still not exatly what we want. We want to give arguments like action=start town=nowhere and we want then to work with the variables $action and $town It's possible! We'll only have to write some lines of code to achieve this: getvariables.php
# 1: <?
We call this script with
php getvariables.php action=start town=nowhere
What happens here is:The script sees "action=start town=nowhere" as two arguments and stuffs them in the $argv array. Now we loop through the $argv array and split every argument in to an array if it contains a "=":
foreach($argv as $arg) {
list($argname, $argval) = split("=",$arg);
and then we assign the second element that contains our value the variable name of the first element:
$$argname = $argval;
The double $$ means that we create a variable that has the name $argname.
So we get an output like this: Action is start Town is nowhereNote that the output will be exactly the same if we call the script like this php getvariables.php town=nowhere action=start
|
||
| Previous:Getting started | Next:Using *NIX tools in your script | |
| .GR - Domains for you |
No residence restrictions - anybody can register
Registration starting at € 16,33 / year
Web Hosting incl. .gr-Domain from € 8,90 / month
|