Call PHP function from url?

If I want to execute a php script, i just point the browser to www.something.com/myscript.php

But if i want to execute a specific function inside myscript.php, is there a way? something like www.something.com/myscript.php.specificFunction

Thanks!


Solution 1:

One quick way is to do things like

something.com/myscript.php?f=your_function_name

then in myscript.php

if(function_exists($_GET['f'])) {
   $_GET['f']();
}

But please, for the love of all kittens, don't abuse this.

Solution 2:

What your script does is entirely up to you. URLs cannot magically cause Apache, PHP, or any other server component to take a certain behavior, but if you write your program such that a particular function can be executed, it's certainly possible. Perhaps something like:

switch($_GET['function']) {
case 'specificFunction':
    specificFunction();
}

Then you could visit myScript.php?function=specificFunction

Be extremely careful here to specifically list each allowable function. You must not just take the $_GET['function'] parameter and blindly execute whatever function it says, since that could present an enormous security risk.

Solution 3:

You will have to expose it in some way. This is because exposing all methods public, would be a security risk.

Example.php

<?php

    function CalculateLength($source)
    {
        return strlen($source);
    }

    if(isset($_GET['calculate-length']) && isset($_GET['value']){
        die(CalculateLength($_GET['value']));
    }

?>

Then just call:

http://www.example.com/Example.php?calculate-length&value=My%20example

Solution 4:

Try this one

$urlParams = explode('/', $_SERVER['REQUEST_URI']);
$functionName = $urlParams[2];
$functionName($urlParams);


function func1 ($urlParams) {
    echo "In func1";
}

function func2 ($urlParams) {
    echo "In func2";
    echo "<br/>Argument 1 -> ".$urlParams[3];
    echo "<br/>Argument 2 -> ".$urlParams[4];
}

and the urls can be as below
http://domain.com/url.php/func1
http://domain.com/url.php/func2/arg1/arg2