7

How can I run several PHP scripts from within another PHP script, like a batch file? I don't think include will work, if I understand what include is doing; because each of the files I'm running will redeclare some of the same functions, etc. What I want is to execute each new PHP script like it's in a clean, fresh stack, with no knowledge of the variables, functions, etc. that came before it.

Update: I should have mentioned that the script is running on Windows, but not on a web server.

Charles
  • 539
  • 1
  • 3
  • 11

4 Answers4

10

You could use the exec() function to invoke each script as an external command.

For example, your script could do:

<?php

exec('php -q script1.php');
exec('php -q script2.php');

?>

Exec has some security issues surrounding it, but it sounds like it might work for you.

zombat
  • 92,731
  • 24
  • 156
  • 164
  • 1
    what does -q do? Is it relevant still? I was looking up man pages and it executes it quietly. What does that mean? Supresses output or something? – Fallenreaper Feb 11 '13 at 03:52
6

// use exec http://www.php.net/manual/en/function.exec.php

<?php

exec('/usr/local/bin/php somefile1.php');
exec('/usr/local/bin/php somefile2.php');

?>

In the old days I've done something like create a frameset containing a link to each file. Call the frameset, and you're calling all the scripts. You could do the same with iframes or with ajax these days.

artlung
  • 33,305
  • 16
  • 69
  • 121
3

exec() is a fine function to use, but you will have to wait until termination of the process to keep going with the parent script. If you're doing a batch of processes where each process takes a bit of time, I would suggest using popen().

The variable you get creates a pointer to a pipe which allows you to go through a handful of processes at a time, storing them in an array, and then accessing them all with serial speed after they're all finished (much more concurrently) using steam_get_contents().

This is especially useful if you're making API calls or running scripts which may not be memory-intensive or computationally intensive but do require a significant wait for each to complete.

Robert Elwell
  • 6,598
  • 1
  • 28
  • 32
3

If you need any return results from those scripts, you can use the system function.

$result = system('php myscript.php');
$otherresult = system('php myotherscript.php');
TJ L
  • 23,914
  • 7
  • 59
  • 77