Forum Moderators: coopster
$string = "foo=a&bar=b";
parse_str($string, $output);
foreach ($output as $key => $val)
$$key = $val; foreach ($output as $key => $val)
$$key = $val;
$varname = $output['varname'] ? null;
$string = "foo=a&bar=b";
parse_str($string, $output);
extract($output); parse_str($_SERVER['QUERY_STRING']);
if (!$foo) {
$query = sprintf("SELECT foo FROM table WHERE username='%' LIMIT 1",
mysqli_real_escape_string($dbh, $username));
$sth = mysqli_query($dbh, $query);
if ($sth !== false)
list($foo) = mysqli_fetch_row($sth);
}
echo <<<EOF
<form action="whatever.php">
<label for="foo">Foo</label>
<input type="text" name="foo" id="foo" value="$foo">
</form>
EOF; without parse_str(), I have to completely redesign a system
parse_str($_SERVER['QUERY_STRING'],$output);
$foo = $output['foo'] ?? null;
$bar = $output['bar'] ?? null;
extract($output);
parse_str($_SERVER['QUERY_STRING']);
[edited by: w3dk at 1:24 pm (utc) on Jan 1, 2021]
Not really, just a few extra lines would "securely" workaround the problem and make the code self-documenting as it's clearer where these variables come from:
The "problem" with these two statements is that the extracted variables will overwrite any that are already defined in the current scope with the same name. So, if I (maliciously) passed a "dbh" parameter in the query string, it would break your DB connection. The extract() function takes a 2nd argument that allows you to control this. And passing the 2nd argument to the parse_str() function prevents this.
Self teaching is great, but, in my opinion, this is good to take programming lessons. This learn you methods of working, and also best practices. When you have a good basis of programming, you can achieve things faster, safer and makes it easier to evolve your code.