Reputation: 142
hello am still learning php and trying to call php function by url link and i did found this code
if(function_exists($_GET['f'])) {
$_GET['f']();
}
but it's not safe for my function so i did something like that
if($_GET['f']=='mouner'){
function mouner(){
$s = 'my name is mouner';
return($s);
}
echo mouner();
}
is that safe code ? and if it's not what is the best way to call function by url with no security risk
Upvotes: 0
Views: 84
Reputation: 30893
Julie has the right answer, just offering up some code cleanup:
if($_GET['f'] == 'mouner'){
$s = 'my name is mouner';
echo $s;
}
If you expect the result to have a lot of variation, could make use of switch()
like so:
if(isset($_GET['f'])){
$s = "My name is ";
switch($_GET['f']){
case 'mouner':
$s .= "Mouner";
break;
}
echo $s;
}
Upvotes: 1
Reputation: 5857
As @JuliePelletier suggested, you need to check your user input before executing any functions associated to it. Another handy way might be something like this:
$funcs["foo"] = function()
{
echo "In foo function";
};
$funcs["bar"] = function()
{
echo "In bar function";
};
if (isset($funcs[$_GET["f"]]))
$funcs[$_GET["f"]]();
Store the functions (either anonymous or just by their name) in an associative array of allowed functions and just execute those.
Upvotes: 5
Reputation: 1716
You are right that the first option is extremely risky, which is why you need to validate user inputs (including GET parameters).
Your second option does exactly that. The code is not perfect but does solve that serious vulnerability.
Upvotes: 3