在后台运行的PHP脚本无法正常工作

时间:2018-11-15 12:28:50

标签: php background exec

我正在尝试在后台运行php脚本,其中包含一个简单的mysql插入查询。但是它没有用,我正在Windows机器上运行。下面是运行脚本背景的代码。

function execInBackground($cmd){
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        pclose(popen("start /B ". $cmd, "r"));  
    }else{ 
        exec($cmd . " > /dev/null &");   
    } 
}  
execInBackground('start cmd.exe @cmd /K php ping.php');

我将此脚本的文件名命名为background.php,而我试图通过background运行的文件是“ ping.php”。哪个也位于同一目录中。以下是我要在本地主机上运行的

网址
http://localhost/adeptra/background.php

我在哪里做错了?任何帮助将不胜感激

调试后,我在命令提示符下发现了这个问题

PHP Fatal error:  Uncaught Error: Call to undefined function mysql_connect() in D:\xampp\htdocs\adeptra\ping.php:10
Stack trace:
#0 {main}
  thrown in D:\xampp\htdocs\adeptra\ping.php on line 10

Fatal error: Uncaught Error: Call to undefined function mysql_connect() in D:\xampp\htdocs\adeptra\ping.php:10
Stack trace:
#0 {main}
  thrown in D:\xampp\htdocs\adeptra\ping.php on line 10

D:\xampp\htdocs\adeptra>$conn = mysql_connect("localhost","root","");
'$conn' is not recognized as an internal or external command,
operable program or batch file.

I tried with mysql and mysqli both . Got same error 

1 个答案:

答案 0 :(得分:0)

您可以检查以下代码,它将为您提供帮助。对我来说有用。您可以在此处进行同样的http://php.net/manual/en/function.popen.php

检查
function execInBackground($cmd){
    if (substr(php_uname(), 0, 7) == "Windows"){ 
        $timer = popen("start /B ". $cmd, "r"); 
        sleep(15);
        pclose($timer);
    }else{ 
        exec($cmd . " > /dev/null &");   
    } 
}

execInBackground("php ping.php");