Hello experts,
Trying to figure out why the very simple script below doesn't do what I think it should. A week of intense googling and experimenting didn't help. Any hints are appreciated.
I have test.php:
<?php
print "foo\n";
print system("php -v");
?>
When called from command line, the script behaves as expected:
- prints "foo"
- calls system()
- system() calls "php -v"
- "php -v" prints the PHP version
- last line of the version output returned by the system() and printed again
> php -q test.php
foo
PHP 4.4.9 (cgi) (built: Aug 12 2008 13:28:34)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2004 Zend Technologies
Zend Engine v1.3.0, Copyright (c) 1998-2004 Zend Technologies>
However, when I call the same script via GET request, it goes into some weird recursion. It prints the "foo", then prints 2 HTTP headers, then "foo" again, and so on until the web-server kills it.
What I tried so far:
- using php5 and php6 in the system() call
- redirecting STDIN and STDERR of the "php -v" to a file - I see the recursion there as well, and right before it dies, there are some errors about not being able to fork (?)
- using exec() instead of system() - slightly different output but the same unexpected recursion
- using shell_exec()/backticks - also getting recursion
- replacing "php -v" with "echo bar" - it works
- replacing "php -v" with "perl -v" - also works
So, it looks like the issue only happens with calling PHP CLI from within PHP CGI (?). Looks like instead of just spawning /usr/local/bin/php as a separate process with it's own command line input, it somehow jumps to the top of the parent script. Note, the server this was tested on is not using safe mode.
The end goal is not to get the PHP version of course, it is to execute an external PHP script. Unfortunately, I am not able to use any other method to execute it (include, load as a file and then eval(), etc.). Must be the system() call. So, please don't suggest alternative solutions, I do know them, but must find a way to use system() for this.
Thanks !