exec 是 PHP 中的一个函数,用于执行外部命令
/usr/bin/php 代替 php。exec('/usr/bin/php your_script.php', $output, $return_var); file_exists() 函数检查命令是否存在于系统中。if (file_exists('/usr/bin/php')) { exec('/usr/bin/php your_script.php', $output, $return_var); } else { echo "PHP executable not found."; } 检查用户权限:确保 PHP 脚本和正在执行的外部命令具有适当的权限。通常,使用 www-data 用户运行 Web 服务器,因此需要确保 PHP 脚本和外部命令可以由该用户执行。
使用 shell_exec():与 exec() 类似,但 shell_exec() 会将整个命令输出返回给 PHP 脚本。这有助于调试和了解命令执行情况。
$output = shell_exec('/usr/bin/php your_script.php'); echo "<pre>$output</pre>"; 2>&1 将错误输出重定向到标准输出,以便在 $output 变量中捕获所有输出。同时,检查 exec() 或 shell_exec() 的返回值,以确定命令是否成功执行。exec('/usr/bin/php your_script.php 2>&1', $output, $return_var); if ($return_var === 0) { echo "<pre>$output</pre>"; } else { echo "Error: Command execution failed."; } set_time_limit():在执行耗时的 PHP 脚本时,使用 set_time_limit() 函数设置合适的超时时间,以防止脚本运行时间过长。set_time_limit(30); // 设置脚本最大执行时间为 30 秒 passthru():如果只需要执行外部命令并实时查看输出,可以使用 passthru() 函数。passthru('/usr/bin/php your_script.php'); 通过遵循这些建议,可以提高使用 PHP exec() 函数处理稳定性的能力。