35

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!

Qazi
  • 5,015
  • 8
  • 42
  • 62
Gabriel
  • 5,453
  • 14
  • 63
  • 92

14 Answers14

58

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.

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
  • 69
    No, no, no, no, no, no, no, no, no! You've just allowed any visitor to execute any PHP function they want! What if they choose to execute your `purgeDatabase` function? Or even just `phpinfo`? – VoteyDisciple Dec 05 '10 at 17:43
  • See below for a class-based alternative which would prevent many of those security concerns. – CodeJoust Dec 05 '10 at 17:44
  • 8
    That's why I said it's a quick way, I'll bold it for you. – Andreas Wong Dec 05 '10 at 17:44
  • Security vulnerabilities ftw! – Robin Orheden Dec 05 '10 at 17:46
  • 3
    The OP didn't ask whether or not this was a good idea, they asked how to do it. This is a quick and dirty solution that gets the job done - perhaps a way to make it better would be to whitelist those functions that are deemed "callable" and only invoke those. Still this is a good answer as it sets the OP down the right path. – Andrew Hare Dec 05 '10 at 17:48
  • 4
    It is quick, but so would be `exec($_GET['foo']);` Surely we're not proposing that efficiency of coding is more important than security. – VoteyDisciple Dec 05 '10 at 19:38
  • 5
    + 1 for the kittens and the answer – Maarten Hartman Feb 02 '13 at 19:40
  • Better would be for security reason if (if(function_exists($_GET['f']) && $_GET['f'] == "some_function_name" ) {...) { else die;} – Marin Sagovac May 11 '14 at 03:55
  • if we add something extra like $_GET['f'] . Action(); then ok? – Katty Apr 07 '17 at 12:02
  • I think "But please, for the love of all kittens, don't abuse this" should be also be bold to highlight the possible dangers of allowing functions to be called from the URL. – 2147483647 May 14 '20 at 01:58
25

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.

VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
12

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

Balaji
  • 345
  • 2
  • 8
11

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
Robin Orheden
  • 2,714
  • 23
  • 24
  • Yes, i'm aware of that. But sometimes is handy when developing. Did not think about using this for production. – Gabriel Dec 05 '10 at 18:47
9

You could do something like this (not recommended for security reasons): www.exampe.com/myscript.php?run=getNames

then:

<?php
if (isset($_GET['run']) && function_exists($_GET['run'])){
  echo $_GET['run']();
} else {
  echo 'Function not Found';
}

You would be better off using a php class instead of trying to call a function on the global namespace because they could call a potenitally dangerous function or call a function you don't want them to see the result to:

<?php
class PublicView {
  function get_page(){ echo 'hey'; }
}
if (isset($_GET['run']) && method_exists('PublicView',$_GET['run'])){
  $view = new PublicView();
  $view->$_GET['run']();
} else {
  echo 'Function not found';
}

This also wouldn't allow the class's private functions to be called, etc.

CodeJoust
  • 3,760
  • 21
  • 23
  • Hi. Im not sure if you are familiar with Android, but as you call a webservice url through android, it wouldnt be visible to the user. Will using this code you posted still cause security problems? – SleepNot Sep 26 '13 at 02:10
6

Here you go. This one is really simple. It calls only specific functions and does default function.

    <?php 

if (isset($_GET['p'])) $linkchoice=$_GET['p']; 
else $linkchoice=''; 

switch($linkchoice){ 

case 's' : 
    firstfunc(); 
    break; 

case 'second' : 
    secondfunc(); 
    break; 

default : 
    echo 'no function'; 

} 

?> 
Simon
  • 1,314
  • 4
  • 14
  • 26
5

I am using this on my website. To use this simply format your url like this www.something.com/myscript.php?function=myFunction&arg=foo&otherarg=bar It doesn't matter what you call the args in the url and you can have as many args as you want.

<?php
        if(isset($_GET["function"])&&!empty($_GET)){
            $function = $_GET["function"];
            unset($_GET["function"]);
            $canexec = array(
                "function name that can be executed",
                "function name that can be executed",
                "function name that can be executed"
            );
            if(!in_array($function,$canexec)){
                die("That function cannot be executed via url.");
            }
            $args = array();
            if(count($_GET)>0){
                //handle args
                foreach($_GET as $arg){
                   array_push($args,$arg);
                }
            }
            $result = call_user_func_array($function,$args);
            //this part is only necessary if you want to send a response to a http request.
            if(is_bool($result)){
                die(($r)?'true':'false');
            }
            else if(is_array($result)){
                die(json_encode($result));
            }
            else {
                die($result);
            }
        }
        myFunction($foo,$bar){
            echo $foo." ".$bar;
        }
    ?>
Somebody
  • 333
  • 3
  • 12
2

you could put the function call in the script.

myFunction();

function myFunction() { .... }

Freddie
  • 1,717
  • 2
  • 16
  • 23
  • If you do it this way, then the script would run that function every time it was called. That could be a mess, especially if you have more than one function in the file. I think the OP is asking about creating a PHP file with multiple functions in it, and only calling one specifically. – ShiningLight Mar 05 '15 at 19:32
1
//Register Hooks
$hooks = ['lang','score'];


function parseHook() {
   if (isset($_GET['_h'])) {
       return $hook = explode('/', filter_var(rtrim($_GET['_h'], '/'), FILTER_SANITIZE_URL));
   } else {
       return false;
   }
}


$hook = parseHook();


if ($hook && in_array($hook[0],$hooks) && function_exists($hook[0])) {
    $callMe = $hook[0];
    unset($hook[0]);
    $params = $hook ? array_values($hook) : [];
    $callMe($params);
}

function lang($params) {
    $Lib = new Lib();
    $Lib->printWithPreTag($params);
}

function score($params) {
    $Lib = new Lib();
    $Lib->printWithPreTag($params);
}

//&_h=hookname/par1/par2/par3
0

Use the constructor of your PHP Class:

<?php
class YourClass {

    function __construct() {
        $functionName = myFunction;

        if (isset($_GET['functionName']) 
                && $_GET['functionName'] == $functionName)){

            myFunction();
        }
        else {
            echo "Function not found";
        }
    }
}
Peter
  • 31
  • 5
0

You cannot do this without adding special code to the PHP file itself to grab the name of the function from the URL and invoking it.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
0

There are several ways.

One way would be to pass the function name as a GET Parameter, and depending on it's existence you could call the function.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
0
 if (isset($GET[param_name])){

  if($GET[param_name] === value)
   {
      function 1... 
    } else if 
 {

function 2...
 }

}
CodeBlooded
  • 185
  • 5
  • 16
robert
  • 1
  • Hello @robert, and welcome to StackOverflow. While your code may help answering the question, it is always better to include some explanation in your answer. That way, the OP and anybody else reading this answer might get a better understanding on how to solve the problem. – dhh Sep 26 '15 at 19:55
0

You could also for security, check the HTTP Referrer. And only execute functions if the referrer is the same domain as itself. Perhaps also compare / check verious other things.

But there should be many ways you can verify the request is coming from the same website were the function needs to be executed.