How do i stop a php script from running in the background?

    Table of contents
  • How do I stop a PHP script running on the background
  • Stopping a php script that's running in the background
  • How to Run PHP Scripts In The Background – Simple Examples
  • How to run a php script in the background

How do I stop a PHP script running on the background

<?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); 
?>
<?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');

?>
<?php
$cpid = posix_getpid();
exec("ps aux | grep -v grep | grep apache", $psOutput);
if (count($psOutput) > 0)
{
    foreach ($psOutput as $ps)
    {
        $ps = preg_split('/ +/', $ps);
        $pid = $ps[1];

        if($pid != $cpid)
        {
          $result = posix_kill($pid, 9); 
        }
    }
}
?>
sudo service apache2 stop
sudo service apache2 start
sudo service apache2 start
sudo service apache2 restart

Stopping a php script that's running in the background

<?php
$count = 0;
while(true){
    $count = $count + 1;
    file_put_contents('daemon1.log', $count, FILE_APPEND);
    sleep(1);

}
?>
ignore_user_abort
connection_aborted

How to run a php script in background

Syntax : {command} &

Example: ls -l & exec php index.php > /dev/null 2>&1 & echo $
ps -l (list all process)
ps -ef (all full details of process)
Syntax: nohup exec arg1 arg2 > /dev/null &

Example: nohup exec php process.php hello world > /dev/null &
$proc=new BackgroundProcess('exec php <BASE_PATH>/process.php hello world');
$proc=new BackgroundProcess();
$proc->setCmd('exec php <BASE_PATH>/process.php hello world');
$proc->start();
$proc=new BackgroundProcess();
$proc->setCmd('exec php <BASE_PATH>/process.php hello world')->start();
$process=new BackgroundProcess("curl -s -o <Base Path>/log/log_storewav.log <PHP URL to execute> -d param_key=<Param_value>");
$proc=new BackgroundProcess();
print_r($proc->showAllPocess());
$proc=new BackgroundProcess();
$proc->setProcessId(101)->stop(); //set the process id.

How to Run PHP Scripts In The Background – Simple Examples

<?php
// (A) COMMAND LINE ONLY!
if (isset($_SERVER["REMOTE_ADDR"]) || isset($_SERVER["HTTP_USER_AGENT"]) || !isset($_SERVER["argv"])) {
  exit("Please run this script from command line");
}
 
// (B) THIS DUMMY SCRIPT WILL CREATE A DUMMY TEXT FILE
// BUT YOU DO WHATEVER IS REQUIRED IN YOUR OWN PROJECT...
file_put_contents("dummy.txt", "Background script ran at " . date("Y-m-d H:i:s"));
<?php
// (A) ABSOLUTE PATH TO BACKGROUND SCRIPT
$script = __DIR__ . DIRECTORY_SEPARATOR ."1a-background.php";

// (B) RUN BACKGROUND SCRIPT
// NOTE: PHP_OS_FAMILY IS AVAILABLE IN PHP 7.2+ ONLY
switch (strtolower(PHP_OS_FAMILY)) {
  // (B1) UNSUPPORTED OS
  default:
    echo "Unsupported OS";
    break;
 
  // (B2) WINDOWS
  case "windows":
    echo "Windows";
    pclose(popen("start /B php $script", "r"));
    break;
 
  // (B3) LINUX
  case "linux":
    echo "Linux";
    exec("php $script > /dev/null &");
    break;
}
CREATE TABLE `tasks` (
  `user_id` int(11) NOT NULL,
  `process_id` varchar(24) NOT NULL,
  `task_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `tasks`
  ADD PRIMARY KEY (`user_id`),
  ADD KEY `task_date` (`task_date`);
<?php
class Background {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo = null;
  private $stmt = null;
  public $error = "";
  function __construct () {
    try {
      $this->pdo = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET, 
        DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
      );
    } catch (Exception $ex) { exit($ex->getMessage()); }
  }

  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct () {
    if ($this->stmt!==null) { $this->stmt = null; }
    if ($this->pdo!==null) { $this->pdo = null; }
  }

  // (C) START A BACKGROUND SCRIPT
  function start ($uid, $script) {
    // (C1) CHECK IF USER ALREADY HAS A RUNNING PROCESS
    $this->stmt = $this->pdo->prepare("SELECT * FROM `tasks` WHERE `user_id`=?");
    $this->stmt->execute([$uid]);
    $check = $this->stmt->fetch();
    if (is_array($check)) {
      $this->error = "User already has a running process.";
      return false;
    }
    
    // (C2) RUN SCRIPT IN BACKGROUND
    // start /B wmic process call create "PATH/PHP.EXE -f PATH/SCRIPT.PHP USER-ID | find ProcessId"
    $cmd = sprintf('start /B wmic process call create "%s -f %s %u | find ProcessId"',
      PHP_PATH, $script, $uid
    );
    $fp = popen($cmd, "r");

    // (C3) GET PROCESS ID - WORKS ON WINDOWS 10
    // BUT MAY DIFFER ON OTHER VERSIONS, YOU MAY NEED TO TWEAK THIS PART ACCORDINGLY
    $processID = 0;
    while (!feof($fp)) {
      $line = fread($fp, 1024);
      if (strpos($line, "ProcessId") !== false) {
        preg_match('/\d+/',$line, $processID);
        $processID = $processID[0];
      }
    }
    pclose($fp);

    // (C4) REGISTER ENTRY
    $this->stmt = $this->pdo->prepare("INSERT INTO `tasks` (`user_id`, `process_id`) VALUES (?,?)");
    $this->stmt->execute([$uid, $processID]);

    // (C5) DONE
    return true;
  }

  // (D) BACKGROUND SCRIPT HAS ENDED
  function end ($uid) {
    $this->stmt = $this->pdo->prepare("DELETE FROM `tasks` WHERE `user_id`=?");
    $this->stmt->execute([$uid]);
    return true;
  }
  
  // (E) KILL TASK
  function kill ($uid) {
    // (E1) CHECK IF USER HAS PENDING TASK
    $this->stmt = $this->pdo->prepare("SELECT * FROM `tasks` WHERE `user_id`=?");
    $this->stmt->execute([$uid]);
    $task = $this->stmt->fetch();
    if (!is_array($task)) {
      $this->error = "User does not have any pending tasks.";
      return false;
    }

    // (E2) WINDOWS KILL TASK
    pclose(popen("taskkill /PID ".$task['process_id']." /F", "r"));

    // (E3) CLOSE ENTRY
    $this->end($uid);

    // (E4) DONE
    return true;
  }
}

// (F) SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("PHP_PATH", "c:/xampp/php/php.exe");

// (G) NEW BACKGROUND OBJECT
$BG = new Background();
<?php
// (A) DEMO - USER ID 999 WANTS TO EXPORT A DUMMY REPORT
// NOTE: USE ABSOLUTE PATH TO SCRIPT
$uid = 999;
$script = __DIR__ . DIRECTORY_SEPARATOR . "2d-background.php";
 
// (B) RUN!
require "2b-bg-core.php";
echo $BG->start($uid, $script)
  ? "RUNNING!" : $BG->error ;
<?php
// (A) COMMAND LINE ONLY!
if (isset($_SERVER["REMOTE_ADDR"]) || isset($_SERVER["HTTP_USER_AGENT"]) || !isset($_SERVER["argv"])) {
  exit("Please run this script from command line");
}

// (B) THIS DUMMY SCRIPT WILL CREATE A DUMMY TEXT FILE
// BUT YOU DO WHATEVER IS REQUIRED IN YOUR OWN PROJECT...
file_put_contents("dummy.txt", "Background script ran at " . date("Y-m-d H:i:s"));

/// FOR TESTING $BG->KILL(), IF YOU WANT THIS SCRIPT TO "HANG"
// sleep(99999);

// (C) REMEMBER TO "END" THE TASK IN THE DATABASE
require __DIR__ . DIRECTORY_SEPARATOR . "2b-bg-core.php";
$BG->end($argv[1]);
<?php
// DEMO - KILL USER ID 999 TASK
require "2b-bg-core.php";
echo $BG->kill(999)
  ? "KILLED" : $BG->error ;

How to run a php script in the background

exec ('/usr/bin/php path/to/script.php >/dev/null &');
<?php


function backgroundProcess($cmd) {
    // windows
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r")); 
    // linux
    } else {
        exec($cmd . " > /dev/null &");  
    }
}

Next Lesson PHP Tutorial

How do I stop a PHP script from running?

The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script.

Can a PHP script run forever?

You can make it run forever by either setting the value or call set_time_limit in your script (http://php.net/manual/en/function.set-time-limit.php).

How kill all PHP processes in Linux?

kill all php, nginx, mysql or any kind of processes.
To kill all PHP Processes. kill $(ps aux | grep '[p]hp' | awk '{print $2}').
To kill all Nginx Processes. kill $(ps aux | grep '[n]ginx' | awk '{print $2}').
To kill all MySQL Processes. kill $(ps aux | grep '[m]ysql' | awk '{print $2}').

Can PHP run in the background?

So, to run any background process from PHP, we can simply use either exec or shell_exec function to execute any terminal command and in that command, we can simply add & at the last so that, the process can run in the background.