开发者

How to sandbox a request to another PHP script?

I have a primarily Ajax-driven site, the content of which is populated by making requests to an "operator" PHP script.

While typically these requests originate in Javascript, there are occasions when it's useful to query my operator from within another PHP script.

The method I have been using is to pass a URL with query string through file_get_contents() — and then to parse the returned JSON with json_decode().

For multiple reasons, I'd like to avoid this implementation, though... I see in my error logs that the URL requests are a lot more susceptible to failure for whatever 开发者_如何学Pythonreason — and I've read that it's not very efficient.

My 1st attempt to make a generic query_operator($query_string)-type function simply require()-ed operator.php within an output buffer, captured with ob_get_contents(). I also temporarily reset the $_REQUEST array with parameters parsed from the $query_string.

This approach had too many shortcomings — problems with variable scope and the MySQL connection, specifically.

My 2nd attempt involved using the backtick operator (equivalent to shell_exec()), and mapping the $argv arguments to the $_REQUEST array.

This approach actually works very well, but on the host I'm using, the PHP (cli) version is set a 4.4.8 — and I need 5.2.x. Assuming I can't switch the (cli) version, what's the next best way to sandbox a request to another PHP script, with a query string? Any suggestions greatly appreciated.

Here's what my 2nd attempt looks like:

function query_operator($query) {
    $query = '--'.str_ireplace('&', ' --', $query);
    $contents = `php operator.php $query`;
    if ($json = json_decode($contents, true)) {
        return $json;
    } else {
        return $contents;
    }
}


The best thing to do, in the long run, is to factor your code.

Whatever logic operator.php is doing that is needed should live in some library, which can then be used by operator.php and any other script that needs it.

When you do that, you'll avoid all the overhead of an extra PHP process, communication between two processes, and probably all your json-encoding/decoding.

If factoring is too much work to take on now, either of the strategies you describe should work as a kludge. It might be worth looking into why your make-a-loopback-http-request method (the first thing you described) caused errors. It really ought to work well, even if it's inefficient.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜