插件窝 干货文章 php可执行哪些系统命令

php可执行哪些系统命令

函数 执行 命令 output 720    来源:    2025-03-16

PHP 可以通过多种方式执行系统命令,但需要注意的是,执行系统命令可能会带来安全风险,特别是在处理用户输入时。以下是一些常见的 PHP 函数和方法来执行系统命令:

1. exec()

exec() 函数用于执行外部程序,并返回最后一行输出。

$output = exec('ls -l');
echo $output;

2. shell_exec()

shell_exec() 函数通过 shell 环境执行命令,并以字符串形式返回完整的输出。

$output = shell_exec('ls -l');
echo $output;

3. system()

system() 函数执行外部程序并显示输出,直接输出到浏览器。

system('ls -l');

4. passthru()

passthru() 函数执行外部程序并直接输出原始输出。

passthru('ls -l');

5. popen()

popen() 函数打开一个进程文件指针,允许你读取或写入到进程。

$handle = popen('ls -l', 'r');
while (!feof($handle)) {
    echo fgets($handle);
}
pclose($handle);

6. proc_open()

proc_open() 函数提供了更高级的控制,允许你与进程进行交互。

$descriptorspec = array(
   0 => array("pipe", "r"),  // 标准输入
   1 => array("pipe", "w"),  // 标准输出
   2 => array("pipe", "w")   // 标准错误
);

$process = proc_open('ls -l', $descriptorspec, $pipes);

if (is_resource($process)) {
    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    echo stream_get_contents($pipes[2]);
    fclose($pipes[2]);

    proc_close($process);
}

7. backticks (反引号)

PHP 还支持使用反引号来执行系统命令,类似于 shell_exec()

$output = `ls -l`;
echo $output;

安全注意事项

  • 避免直接使用用户输入:永远不要直接将用户输入传递给这些函数,否则可能会导致命令注入漏洞。
  • 使用 escapeshellarg()escapeshellcmd():这些函数可以帮助转义用户输入,减少命令注入的风险。
$user_input = escapeshellarg($_GET['input']);
$output = shell_exec('ls ' . $user_input);
echo $output;

总结

PHP 提供了多种方式来执行系统命令,但必须谨慎使用,特别是在处理用户输入时。确保对输入进行适当的验证和转义,以防止安全漏洞。