Filesystem 函数
PHP Manual

popen

(PHP 4, PHP 5)

popen打开进程文件指针

说明

resource popen ( string $command , string $mode )

打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。

返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets()fgetss()fwrite()

如果出错返回 FALSE

Note:

如果需要双向支持,使用 proc_open()

Example #1 popen() 例子

<?php
$handle 
popen("/bin/ls""r");
?>

Note:

如果未找到要执行的命令,会返回一个合法的资源。这看上去很怪,但有道理。它允许访问 shell 返回的任何错误信息:

<?php
error_reporting
(E_ALL);

/* 加入重定向以得到标准错误输出 stderr。 */
$handle popen('/path/to/spooge 2>&1''r');
echo 
"'$handle'; " gettype($handle) . "\n";
$read fread($handle2096);
echo 
$read;
pclose($handle);
?>

Note: 安全模式 启用时,可仅可用 safe_mode_exec_dir 执行文件。实际上,现在不允许在到可执行的路径中存在 .. 组件。

Warning

安全模式 启用时,命令字符串会被 escapeshellcmd() 转换。因此, echo y | echo x 会变成 echo y \| echo x

参见 pclose()fopen()proc_open()

参数

command

The command

mode

The mode

返回值

Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.

If an error occurs, returns FALSE.

范例

Example #2 popen() example

<?php
$handle 
popen("/bin/ls""r");
?>

If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:

Example #3 popen() example

<?php
error_reporting
(E_ALL);

/* Add redirection so we can get stderr. */
$handle popen('/path/to/executable 2>&1''r');
echo 
"'$handle'; " gettype($handle) . "\n";
$read fread($handle2096);
echo 
$read;
pclose($handle);
?>

注释

Note:

If you're looking for bi-directional support (two-way), use proc_open().

Note: 安全模式 启用时,可仅可用 safe_mode_exec_dir 执行文件。实际上,现在不允许在到可执行的路径中存在 .. 组件。

Warning

安全模式 启用时,命令字符串会被 escapeshellcmd() 转换。因此, echo y | echo x 会变成 echo y \| echo x

参见


Filesystem 函数
PHP Manual