Luis Ramos
Luis Ramos

Reputation: 73

PHP exec function does not work well

First of all use windows.

I have the following code:

index.php

<?php
    error_reporting(E_ALL);
    $tiempo_inicio = microtime(true);
    exec('C:\wamp\bin\php\php5.5.12\php.exe -e C:\wamp\www\mail.php  > /dev/null &');  
    $tiempo_fin = microtime(true);
    echo ($tiempo_fin - $tiempo_inicio);
    ?>

Mail.php

<?php
$tiempo_inicio = microtime(true);
    $logs = fopen("test.txt","a+"); 
    sleep(2);
    $tiempo_fin = microtime(true);
    fwrite($logs, ($tiempo_fin - $tiempo_inicio)."
    "); 
    sleep(4);
    $tiempo_fin = microtime(true);
    fwrite($logs, ($tiempo_fin - $tiempo_inicio)."
    ");
    sleep(6);
    $tiempo_fin = microtime(true);
    fwrite($logs, ($tiempo_fin - $tiempo_inicio)."
    ");
    echo 'fin';
?>

But it does not work I hope, because what I want is to run the file in the background without the user wait for the completion of this file.

What am I doing wrong?

Upvotes: 0

Views: 98

Answers (2)

DMartins
DMartins

Reputation: 26

I've had success in the past on Windows using pclose/popen and the Windows start command instead of exec. The downside to this is that it is difficult to react to any errors in the program you are calling.

I would try something like this (I'm not on a machine to test this today):

$command_string = 'C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\mail.php" -- variablestopass';

pclose(popen("start /B ".$command_string, 'r')); 

Upvotes: 0

Machavity
Machavity

Reputation: 31654

You're talking about a non-blocking execution (where one process doesn't wait on another. PHP really can't do that very well (natively anyways) because it's designed around a single thread. Without knowing what your process does I can't comment on this precisely but I can make some suggestions

  • Consider asynchronous execution via AJAX. Marrying your script to a Javascript lets the client do the request and lets your PHP script run freely while AJAX opens another request that doesn't block the activity on the main page. Just be sure to let the user visually know you're waiting on data
  • pthreads (repo)- Multi-threaded PHP. Opens another process in another thread.
  • Gearman - Similar to pthreads but can be automated as well
  • cron job - Fully asynchronous. Runs a process on a regular interval. Consider that it could do, say, data aggregation and your script fetches on the aggregate data

Upvotes: 1

Related Questions