开发者

Calling PHP function with arguments remotely

I have a scenario where in our php file accepts parameters from the command line.

For example we say,

php test.php 'hello'

Now the above runs on command prompt. Suppose now we want to invoke this from client end however ofcourse i do not want the System system call as that would be a bad design, i just want to directly call the function which accepts parameters from the client 开发者_开发问答end and ofcourse client can be anything maybe .Net or PHP so how can I caccomplish that?

Thanks!


Put your script on a web server and accept the argument via HTTP GET or POST.

It would look something like http://hostname/test.php?argument=hello. Then, in your test.phpscript, pass the $_GET['argument'] to your function:

myfunction($_GET['argument']);

Don't forget to sanitize the input!


you may use a function that will manage command line argiments:

$param_1 = isset($argv[1]) ? $argv[1] : null; if ($param_1 == 'function1') function1() elseif...

and so on.


You can make a wrapper script that puts GET parameters from your client into the command line argument array.

Let's say your client makes a request like:

hostname/testWrapper.php?params[]=hello&params[]=goodbye

Your wrapper script testWrapper.php could then look like

<?php
  $params = $_GET['params'];

  foreach ($params as $i => $param)
    $_SERVER['argv'][$i + 1] = $param;

  $_SERVER['argc'] = count($_GET['params'] + 1);

  include ('test.php');
?>

This assumes that your test.php uses $_SERVER['argv/argc']to read command line arguments. It may use $argv and $argc instead (if 'register_argc_argv' is enabled in your php.ini), in which case you just use those in your wrapper script instead of $_SERVER[...].

Notice that we have to insert the parameters with an offset of 1 (i.e. $params[0] becomes $_SERVER['argv'][1]. This is because when the script is called from the command line, the first parameter $_SERVER['argv'][0] is the script name.

Lastly, unless you are absolutely sure that your test.php sanitizes the parameters, you have to do it in the wrapper script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜