1

I wrote a function which runs a php script and returns its output. I wish to know if there's a better way to do this, as this seems like more of a workaround to me. Since the script is local, it seems rather wasteful to use page_get_contents (with a full URL) as that takes more time.

function runpage($path, $query) {
    parse_str($query, $_GET);
    $oldquery = $_SERVER["QUERY_STRING"];
    $_SERVER["QUERY_STRING"] = $query;
    ob_start();
    include $path;
    $out = ob_get_contents();
    ob_end_clean();
    $_SERVER["QUERY_STRING"] = $oldquery;
    return $out;
}

Thanks much!

3
  • Actually it would be less wasteful to use file_get_contents Commented Jan 2, 2011 at 22:44
  • 1
    You forgot to set $_SERVER['QUERY_STRING'] back. Commented Jan 2, 2011 at 22:45
  • @rik: For this particular script I don't use $_SERVER['QUERY_STRING'], however, you are correct. I shall change that. Of course, with that change in effect, the $oldquery variable could be changed by whatever script is run... @Ben: I'm a little confused as to how that would be less wasteful, would you please explain? Commented Jan 2, 2011 at 22:52

1 Answer 1

1

Yes, it is a kludge. No, there isn't a significantly better way.

The whole point of that snippet is to be a workaround. You could very well rewrite the included script, make it read it's input variables from another array and have it return the output correctly over a function call. Or you could turn it into an executable script, and access argv instead of $_GET - but that would require the same amount of restructuring.

Yes, it's awkward. But get over it. Shell scripts and pipes are by no means cleaner than this PHP include (apart from the $_GET override it's similar to templating anyhow). And regardless of that, awkward doesn't mean it's going to fail. Just don't make this a regular construct.

1
  • That's about what I expected, thanks for confirming my suspicions! Commented Jan 2, 2011 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.