Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a PHP script running on the background

Tags:

php

apache

I started this process (time.php)

<?php

ignore_user_abort(true); // run script in background
set_time_limit(0);       // run script forever 
$interval = 300;         // do every 1 minute...
do
{ 
    // add the script that has to be ran every 1 minute here
    // ...

    $to      = "[email protected]";
    $subject = "Hello Richie";
    $header  = "From: [email protected]";
    $body    = "Hello Richard,\n\n"
             . "I was just testing this service\n\n "
             . "Thanks! ";

    mail($to, $subject, $body, $header);

    sleep($interval); // wait 5 minutes

} while(true); 
?>

but I now want to stop it. It's sending hundreds of mail to my Gmail a/c. It's on a web server where I cant restart it to kill the process.

Is there a way to execute another file to kill the process, or how do I go about?

like image 776
Richie Avatar asked Dec 12 '12 19:12

Richie


1 Answers

If you don't have shell access, then the only way is to ask the server administrater to kill the process.

That being said, there is an easy way to set up a script and enable it to be canceled from any other script on the same server, as follows:

<?php
// at start of script, create a cancelation file

file_put_contents(sys_get_temp_dir().'/myscriptcancelfile','run');

// inside the script loop, for each iteration, check the file

if ( file_get_contents(sys_get_temp_dir().'/myscriptcancelfile') != 'run' ) { 
    exit('Script was canceled') ; 
}

// optional cleanup/remove file after the completion of the loop

unlink(sys_get_temp_dir().'/myscriptcancelfile');

// To cancel/exit the loop from any other script on the same server

file_put_contents(sys_get_temp_dir().'/myscriptcancelfile','stop');

?>
like image 149
Eric P Avatar answered Sep 17 '22 01:09

Eric P