-2

Hello Id like to know how to call the function I just written from URL? Bellow are my php code.

<?php
require 'db.php';

function l1(){
    echo "Hello there!";
}

function l2(){
    echo "I have no Idea what Im doing!";
} 
function l3(){
    echo "I'm just a year 1 college student dont torture me sir!";
}


?>

I tried http://127.0.0.1/study/sf.php?function=l1 but it wont echo the written code.

Please point me to the right direction.

learningXD
  • 11
  • 1
  • 3
  • possible duplicate of [How to call PHP function from string stored in a Variable](http://stackoverflow.com/questions/1005857/how-to-call-php-function-from-string-stored-in-a-variable) –  Apr 12 '15 at 12:55
  • 2
    But seriously reconsider this. You don't want to give your visitors the possibility to randomly execute any PHP function somewhere in your code. –  Apr 12 '15 at 12:56
  • *What* do you not get? –  Apr 12 '15 at 13:01

2 Answers2

4

Yes you could supply that parameter into calling your user defined function:

$func = $_GET['function'];
$func();

Might as well filter the ones you have defined thru get_defined_functions

function l1(){
    echo "Hello there!";
}

function l2(){
    echo "I have no Idea what Im doing!";
} 
function l3(){
    echo "I'm just a year 1 college student dont torture me sir!";
}

$functions = $arr = get_defined_functions()['user']; // defined functions

if(!empty($_GET['function']) && in_array($_GET['function'], $functions)) {
    $func = $_GET['function'];
    $func();
}

Sample Output

Sidenote: function_exists can be also applied as well:

if(!empty($_GET['function']) && function_exists($_GET['function'])) {
    // invoke function
}
Kevin
  • 41,694
  • 12
  • 53
  • 70
1

One option you can do if use if/elseifs like so:

if($_GET['function'] == 'l1')
{
    l1();
}
else if($_GET['function'] == 'l2')
{
    l2();
}

Or you could use a riskier approach and call the function name directly from the input.

$functionName = $_GET['function'];
$functionName();

Edit: Or you could use a switch statement:

switch($_GET['function'])
{
    case 'l1':
        l1();
    break;
    case 'l2':
        l2();
    break;
    case 'l3':
        l3();
    break;
}
Mex
  • 1,011
  • 7
  • 16