PHP: passing php variables as arguments?

725

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

47

Answer

Solution:

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

Answer

Solution:

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...)

179

Answer

Solution:

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);
225

Answer

Solution:

Like this:

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

Answer

Solution:

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

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

People are also looking for solutions to the problem: php - Using SHA-256 for CodeIgniter hashing

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.