php实现cmd
PHP 执行 CMD 命令的方法
在 PHP 中可以通过多种方式执行命令行(CMD)命令,以下是几种常见的方法:
使用 exec() 函数
exec() 函数用于执行外部程序并返回最后一行输出。
$output = exec('dir');
echo $output;
使用 shell_exec() 函数
shell_exec() 执行命令并返回完整的输出字符串。

$output = shell_exec('dir');
echo $output;
使用 system() 函数
system() 执行外部程序并显示输出。
system('dir');
使用 passthru() 函数
passthru() 执行外部程序并显示原始输出。

passthru('dir');
使用 proc_open() 函数
proc_open() 提供了更高级的控制,可以处理输入、输出和错误流。
$descriptors = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$process = proc_open('dir', $descriptors, $pipes);
if (is_resource($process)) {
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($process);
}
使用反引号运算符
反引号(`)运算符与 shell_exec() 功能相同。
$output = `dir`;
echo $output;
注意事项
- 执行外部命令可能存在安全风险,特别是当命令中包含用户输入时。务必使用
escapeshellarg()或escapeshellcmd()进行转义。 - 某些函数可能被服务器禁用,具体取决于 PHP 配置。检查
php.ini中的disable_functions设置。 - 在 Windows 系统上,命令可能需要使用
cmd /c前缀。
示例:安全执行用户输入的命令
$userInput = 'dir'; // 假设来自用户输入
$cleanInput = escapeshellcmd($userInput);
$output = shell_exec($cleanInput);
echo $output;
以上方法提供了在 PHP 中执行 CMD 命令的不同方式,选择哪种取决于具体需求和服务器配置。






