PHP Convert variable names to lowercase?
I have an api listener script which takes in get parameters. But I seem to be having issues when users tend to pass mixed case variable names on the parameters.
For example:
http://mylistenerurl.com?paramName1=Hello¶mname2=World
I need my listener to be flixible in such a way that the variable names will be interpreted case-insensitively or rather still all in lower case l开发者_JAVA百科ike after I process the query string on some function, they are all returned as lower-cased variables:
extract(someFunction($_GET));
process($paramname1, $paramname2);
Can anybody shed some light on this?
*much appreciated. thanks!
This should do the trick:
$array_of_lower_case_strings = array_map( "strtolower", array( "This Will Be ALL lowercase.", ... ) );
So in your case:
$get_with_lowercase_keys = array_combine(
array_map( "strtolower", array_keys( $_GET ) ),
array_values( $_GET )
);
One thing I'll mention is you should be VERY careful with extract
as it could be exploited to allow unexpected variables to be injected into your PHP.
Apply to your global variables ($_GET, $_POST) when necessary:
e.g. setLowerCaseVars($_GET);
in your case
function setLowerCaseVars(&$global_var) {
foreach ($global_var as $key => &$value) {
if (!isset($global_var[strtolower($key)])) {
$global_var[strtolower($key)] = $value;
}
}
}
Edit: Note that I prefer this to using array_combine because it will not overwrite cases where the lower-case variable is already set.
PHP has had a native function (array_change_key_case()) for this task since version 4.2 to change the case of first level keys. To be perfectly explicit -- this function can be used to convert first level key to uppercase or lower case BUT this is not a recursive function so deeper keys will not be effected.
Code: (Demo)
parse_str('paramName1=Hello¶mname2=World&fOo[bAR][BanG]=boom', $_GET);
var_export($_GET);
echo "\n---\n";
$lower = array_change_key_case($_GET);
var_export($lower);
Output:
array (
'paramName1' => 'Hello',
'paramname2' => 'World',
'fOo' =>
array (
'bAR' =>
array (
'BanG' => 'boom',
),
),
)
---
array (
'paramname1' => 'Hello', # N changed to n
'paramname2' => 'World',
'foo' => # O changed to o
array (
'bAR' => # AR not changed because not a first level key
array (
'BanG' => 'boom', # B and G not changed because not a first level key
),
),
)
精彩评论