简体   繁体   English

如何使用PHP运行Shell脚本

[英]How to run shell script using php

I have a php file 我有一个php文件

<?php
$op=exec("/usr/bin/sh /home/muralik/www/html/testing/testin.sh >> /home/muralik/www/html/testing/abc.log 2>&1 &",$rs);
echo "OP = ".$op;
echo "<br>RS = <pre>";
print_r($rs);
echo "</pre>"
?>

testin.sh 测试文件

while(true)
do
echo "standard output"
echo "abc"
sleep 2
done

When i open the php file in localhost or web server. 当我在localhost或Web服务器中打开php文件时。 the shell script is not running. Shell脚本未运行。

What should i do. 我该怎么办。 thanks in adavance. 非常感谢。

I believe your script is running, you're just not seeing the output? 我相信您的脚本正在运行,您只是看不到输出?

The command you're running in your exec redirects both STDOUT and STDERR to abc.log: 您在exec中运行的命令会将STDOUT和STDERR都重定向到abc.log:

/usr/bin/sh /home/muralik/www/html/testing/testin.sh >> /home/muralik/www/html/testing/abc.log 2>&1

Because everything is getting redirected, nothing will end up in $rs, and $op will be empty as well as there will be no last line from the executed command. 因为所有内容都被重定向,所以$ rs中不会有任何结果,并且$ op将为空,并且执行的命令将没有最后一行。

Also, your shell script is going to run in an infinite loop, meaning it will never return anything, meaning the exec() should never return as it waits for the execution to finish. 另外,您的shell脚本将在无限循环中运行,这意味着它永远不会返回任何内容,这意味着exec()在等待执行完成时也绝不会返回。

Usually (for security reasons) scripts run from a browser will not run shell commands. 通常(出于安全原因)从浏览器运行的脚本不会运行shell命令。

In order to make it work you need to change your .htaccess file (this will tell your server to treat your script as an appliacation) 为了使其正常工作,您需要更改.htaccess文件(这将告诉您的服务器将脚本视为应用程序)

Add the following lines in your .htaccess: 在您的.htaccess中添加以下行:

Options ExecCGI 
AddHandler cgi-script .php

This will allow any php files in the CGI folder to run as an application 这将允许CGI文件夹中的所有php文件作为应用程序运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM