目前,PHP环境几乎都搭载在Linux环境,有时候,我们需要PHP去执行Linux命令实现一些特殊功能。介绍以下5个PHP执行Linux函数。
exec
返回结果如下
string exec ( string $command [, array &$output [, int &$return_var ]] )
// 琼台博客 www.qttc.net
echo exec("ls");
Array
(
[0] => index.html
[1] => 10.log
[2] => 10.tar.gz
[3] => aaa.tar.gz
[4] => mytest
[5] => test1101
[6] => test1102
)
system
string system ( string $command [, int &$return_var ] )
// 琼台博客 www.qttc.net
echo system("ls");
index.html
10.log
10.tar.gz
aaa.tar.gz
mytest
test1101
test1102
passthru
void passthru ( string $command [, int &$return_var ] )
// 琼台博客 www.qttc.net
$cmd = "ls";
passthru($cmd, $status);
if ($status == 0) {
// success
} else {
// failure
}
proc_open
resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env [, array $other_options ]]] )
// 琼台博客 www.qttc.net
$cwd='/tmp';
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/tmp/error-output.txt", "a")
);
$process = proc_open("time ./a a.out", $descriptorspec, $pipes, $cwd);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
[edan@edan tmp]$ php proc.php
a.out here.
[edan@edan tmp]$ cat /tmp/error-output.txt
real 0m0.001s
user 0m0.000s
sys 0m0.002s
shell_exec
string shell_exec ( string $cmd )
index.html
10.log
10.tar.gz
aaa.tar.gz
mytest
test1101
test1102
以上为5个执行Linux命令的PHP函数。