0

I have a script a.php and I want to call a (long running) script b.php from a.php on my Windows machine.

This is sample file a.php:

<?php
  $command = 'start /B php b.php > NUL';
  pclose(popen($command, 'r'));
?>

and this is sample file b.php

<?php
  sleep(30);
?>

but this doesn't work, a.php waits till b.php is finished.

What can I do to run b.php in the background?

UPDATE

Maybe the problem is not related to how I call b.php but how a.php is called. Here is a more complete example of what I'm doing:

A user calls webservice index.php?cmd=download&source=s1 (I test it with Postman)

index.php:

<?php
  include_once 'a.php';
  if($_GET['cmd'] == "download") {
    $source = $_GET['source'];
    $flag = startDownload($source);
    if($flag) {
      echo("Download was initialized");
    } else {
      echo("Download not started");
    }
  }
?>

a.php:

<?php
  function startDownload($source) {
    if($source == "s1") {
      $command = 'start /B php b.php > NUL';
      pclose(popen($command, 'r'));
    } else {
      $command = 'start /B php c.php > NUL';
      pclose(popen($command, 'r'));
    }
    return true;
  }
?>

b.php:

<?php
  $ch = curl_init();
  $source = "http://example.com/bigfile.zip";
  curl_setopt($ch, CURLOPT_URL, $source);
  $data = curl_exec($ch);
  curl_close($ch);

  $file = fopen("/", "w+");
  fputs($file, $data);
  fclose($file);
?>
Christian Vorhemus
  • 2,396
  • 1
  • 17
  • 29
  • what exactly are you trying to achieve? passing certain parameters to another php file and let it do it's job? – Nikos Gkogkopoulos Feb 23 '18 at 13:39
  • In the first place, b.php should download a large file, a.php should just inform the user that the download was initiated (so a.php should return true after b.php was called) – Christian Vorhemus Feb 23 '18 at 13:44
  • According to user comments from http://php.net/manual/en/function.popen.php you've done it ok. And why you are redirecting output to file called NUL? – DevilaN Feb 23 '18 at 13:45
  • Maybe you can take a look [here](https://stackoverflow.com/questions/4231539/run-a-php-script-as-a-background-process-in-wamp-server) – Jeremy M. Feb 23 '18 at 13:51
  • A PHP script runs at one thread which means that the script is running in 'serial mode'. It is not possible to execute a script parallel to the current script. You should take a look at `cronjobs`. – Ruben Feb 23 '18 at 14:36

0 Answers0