0

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

6
  • You don't need to add echo to your statement when calling a function in php..! Commented May 25, 2016 at 23:52
  • Also you don't need to put your function mouner() { } inside your if function as you may know that way you are declaring the function as local which you may not be able to call to in somewhere else outside your this if function..! Commented May 25, 2016 at 23:54
  • 1
    What do you mean by security risk?? Commented May 25, 2016 at 23:59
  • Also I am still in shock how would even that work as you are writting in your first code as : if (function_exists($_GET['f'])) as if (isset($_GET['f'])) I do know but not yours one..! Commented May 26, 2016 at 0:00
  • 1
    A more concrete example might be helpful... as it stands now you could just execute echo 'my name is mouner'; inside your if and it would be exactly equivalent. Commented May 26, 2016 at 0:01

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this helped me a lot
Haven't seen this done in a long time haha! Got my vote for alternative suggestion ;-)
3

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.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.