0

I'm trying to execute a separate PHP script from within a PHP page. After some research, I found that it is possible using the exec() function.

I also referenced this SO solution to find the path of the php binary. So my full command looks like this:

$file_path = '192.168.1.13:8080/doSomething.php';
$cmd = PHP_BINDIR.'/php '.$file_path; // PHP_BINDIR prints /usr/local/bin
exec($cmd, $op, $er);
echo $er; // prints 127 which turns out to be invalid path/typo

doSomething.php

echo "Hi there!";

I know $file_path is a correct path because if I open its value; i.e. 192.168.1.13:8080/doSomething.php, I do get "Hi there!" printed out. This makes me assume that PHP_BINDIR.'/php' is wrong.

Should I be trying to get the path of the php binary in some other way?

Community
  • 1
  • 1
  • you execute commands just by using backticks. e.g. \`php 192.168.1.13:8080/doSomething.php\` . see that i put 'php' at the front of your path. – adamS Dec 27 '13 at 10:38

1 Answers1

1

The file you are requesting is accessible via a web server, not as a local PHP script. Thus you can get the result of the script simply by

$output = file_get_contents($file_path);

If you however for some reason really have to exec the file, then you must provide a full path to that file in your server directory structure instead of server URL:

$file_path = '/full/path/to/doSomething.php';
$cmd = PHP_BINDIR.'/php '.$file_path;
exec($cmd, $op, $er);
Maciej Sz
  • 11,151
  • 7
  • 40
  • 56
  • I don't really need to get the contents of `$file_path`. I just used a simple "Hi there" to test if `exec` works properly. I'll be replacing that code with a more complex code which I need to be able to run in background. – EnthusiacticProgrammer Dec 27 '13 at 10:42
  • PHP does not natively provide threading functionallity. If you either `exec` or use `file_get_contents` it will be invoked in that exact spot, and rest of your script will wait for it to finish. If you want that script to execute in background, then there is some additional coding involved. – Maciej Sz Dec 27 '13 at 10:44
  • By full path, do you mean something like this : `var/www/somefolder...`? – EnthusiacticProgrammer Dec 27 '13 at 10:46
  • Yes (just with the leading slash `/` in front). Additionally if that script would only be executed from within another script, than don't expose it via web server by moving it outside the root of host directory. – Maciej Sz Dec 27 '13 at 10:50