Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to call a CGI script from a PHP script?

I saw that there is a virtual() function in PHP that will call a CGI script, but is that the best way? Can I pass any parameters to that scripts as well?

I saw some examples using file_get_contents() or include() and passing in the URL of a CGI script, but that feels like a hack.

like image 627
John B Avatar asked Dec 30 '25 22:12

John B


1 Answers

Use exec() if you can call it locally. If it needs to be invoked as a CGI (as in the script is designed to only work within a CGI environment), then you'll need to call it via include() or file_get_contents(). virtual() will flush your buffers and append the output of the sub-request.

You can pass parameters through include(), file_get_contents(), and virtual() as GET parameters:

http://localhost/cgi-bin/foo?param1=val1&param2=val2

If possible, go the exec() route. Using the other methods may require a config change.

When using exec(), you'll need to pass the arguments like you would for any CLI program.

foo val1 val2
foo param1=val1 param2=val2

How you pass the parameters in will depend on how you want to parse them out later in the other program/script. They'll show up in the called program like they would if you called it from the command line.

like image 80
Ryan Graham Avatar answered Jan 02 '26 13:01

Ryan Graham