aneuryzm
aneuryzm

Reputation: 64834

PHP: passing php variables as arguments?

In my php code I need to invoke a script and passing it some arguments. How can I pass php variables (as arguments) ?

$string1="some value";
$string2="some other value";
header('Location: '...script.php?arg1=$string1&arg2=$string2');

thanks

Upvotes: 0

Views: 308

Answers (5)

kieron
kieron

Reputation: 31

You could use the function http_build_query

$query = http_build_query(array('arg1' => $string, 'arg2' => $string2));

header("Location: http://www.example.com/script.php?" . $query);

Upvotes: 3

Marc B
Marc B

Reputation: 360702

Either via string concatenation:

header('Location: script.php?arg1=' . urlencode($string1) . '&arg2=' . urlencode($string2));

Or string interpolation

$string1=urlencode("some value");
$string2=urlencode("some other value");
header("Location: script.php?arg1={$string1}&arg2={$string2}");

Personally, I prefer the second style. It's far easier on the eyes and less chance of a misplaced quote and/or ., and with any decent syntax highlighting editor, the variables will be colored differently than the rest of the string.

The urlencode() portion is required if your values have any kind of url-metacharacters in them (spaces, ampersands, etc...)

Upvotes: 4

Brian
Brian

Reputation: 8616

It should work, but wrap a urlencode() incase there is anything funny breaking the url:

header('Location: '...script.php?'.urlencode("arg1=".$string1."&arg2=".$string2).');

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

Like this:

header("Location: http://www.example.com/script.php?arg1=$string1&arg2=$string2");

Upvotes: 0

hsz
hsz

Reputation: 152216

header('Location: ...script.php?arg1=' . $string1 . '&arg2=' . $string2);

Upvotes: 4

Related Questions