PHP执行后台程序 argv

有时候执行的处理时间比较长,一般情况下,我们都是等程序执行完后再执行下面的处理,但是,有时我们不想让用户等待时间太长,让后面的处理先执行,处理时间长的处理放到后台执行。这次我将说明一下如何在Linux/Unix平台下后台执行PHP程序

执行时间长的程序(test.php) 
<?php 
/* POST提交后、执行需要长时间处理的程序。这里什么也不处理只是停止10s */ 
if ($_POST['submit']) { 
  sleep(10); 
   echo 'finish!'; 
} else { 
?> 
<html> 
执行时间长的程序
<form method="post" action="test.php"> 
<input type="submit" name="submit" value="执行长时间处理的程序"> 
</form> 
</html> 
<?php 

?>

执行这个脚本的,点击”执行长时间处理的程序“的铵钮后,必须经过10S后,才会出现 finish!文字。
现在我们将这个程序改成这样,首先将处理和被处理的部分分成两个文件。

执行时间长的程序(/path/to/exec.php) 
<?php 
sleep(10); 
?>

不需要等待的程序(test2.php) 
<?php 
if ($_POST['submit']) { 
  exec("/usr/local/bin/php /path/to/exec.php > /dev/null &"); 
   echo " finish!"; 
} else { 
?> 
<html> 
执行需要处理很长时间的程序,但不要等待很长时间
<form method="post" action="test2.php"> 
<input type="submit" name="submit" value="执行长时间的处理"> 
</form> 
<?php 

?>

  使用exec函数,在PHP程序中使用命令行来执行PHP程序

 这里重点是在命令的最後加上「 > /dev/null &」。exec函数的参数、/usr/local/bin/php和/path/to/exec.php要根椐自己的开发环境来指定

 如果要在处理的程序向被处理的程序中传递参数的话

接收参数的被处理的程序(/path/to/exec2.php) 
<?php 
//2个参数。顺序的从$argv数组取出。 
$str1 = $argv[1]; 
$str2 = $argv2];                                                                                                                                                           ?>                                                                                                                                                           

//不需要等待的程序
<?php 
if ($_POST['submit']) { 
  $str1 = 'hoge'; //要传递的参数1
  $str2 = 'fuga'; //要传递的参数2
  //escape处理 
  $q_str1 = escapeshellarg($str1); 
  $q_str2 = escapeshellarg($str2); 

  $cmd = '/usr/local/bin/php /path/to/exec.php'. $q_str1 .' '. $q_str2 .' > /dev/null &';                               exec($cmd);              ?>

原文地址:https://www.cnblogs.com/webu/p/2936813.html