-1

Is it possible for me to execute a function in a php file by typing the name of the function in the input texbox of another php file.

function bamiiChuckNorris() {
$arrContextOptions=array(
    "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
        ),
    );
$geocodeUrl = "http://api.icndb.com/jokes/random";
$response = file_get_contents($geocodeUrl, false,     stream_context_create($arrContextOptions));
$a =json_decode($response, true);
return $a['value']['joke'];
}function bamiiTellTime($data) {
if(strpos($data, 'in')) {
    return "Sorry i can't tell you the time somewhere else right now";
} else {
    return 'The time is:' . date("h:i");
}
}?>

This is my file

<?php include answers.php
This is the input text box
<input name="input" type="text" class="tb5" placeholder="Chat with me!   Press Ask to send."?>
Adokiye Iruene
  • 740
  • 2
  • 10
  • 34

2 Answers2

1

Yes, it's possible to dynamically execute function, but make sure it has lots of validations for user to call only valid functions.

$functionName = $_POST['input'];

if (function_exists($functionName)) {
    // Dynamic call using variable value as function name.
    $response = {$functionName}();
} else {
    throw new Exception(404, "Function '{$functionName}' not found");
}

If checking object method, use method_exists($class, $functionName)


To execute code from input like get_number(1) there is few options:

1) Use eval($input) - insecure

2) Parse user input using regex

$uInput = $_POST['input'];

$matches = [];

preg_match('/(\w+)\((\w+)\)/', $uInput, $matches);

$functionName = $matches[1];
$params = $matches[2];

{$functionName}(...explode(', ', $params));
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • If the name of a function is get_number($number) and the number the user inputs get_number(1), how will the function execute – Adokiye Iruene Apr 26 '18 at 07:46
  • @AdokiyeIruene You must pass parameters as different input or parse it using regex, like `/(\w+)\((\w+)\)/`, and `$1` will be function name, `$2` will be parameter. If there is more params, think about splitting `$2` with `explode(', ', $params)` – Justinas Apr 26 '18 at 07:52
  • If the user writes get_number(1), what will be the php code to execute based on your code above – Adokiye Iruene Apr 26 '18 at 07:54
  • Thank you, but can how can i join both function() or function_with_variables($var) in the same code. what is if the user types either functions – Adokiye Iruene Apr 26 '18 at 08:29
  • @AdokiyeIruene Use different regex – Justinas Apr 26 '18 at 08:45
0

This is my solution based on your code @Justinas

$function = $_POST['input'];
    $functionName = explode("(", $function);
    if (function_exists($functionName[0])) {
        $functionVariable = explode(')',$functionName[1],2);
        // Dynamic call using variable value as function name.
        $response = $functionName[0]($functionVariable[0]);
Adokiye Iruene
  • 740
  • 2
  • 10
  • 34