Terminal.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace core\util;
  3. class Terminal
  4. {
  5. /**
  6. * 执行命令
  7. * @param string $cwd 要执行命令的初始工作目录
  8. * @param string $command 要执行的命令
  9. * @return string|true
  10. */
  11. public static function execute(string $cwd, string $command)
  12. {
  13. if (!function_exists('proc_open') || !function_exists('proc_close')) return 'Function proc_open or proc_close disabled';
  14. // 设置执行时长
  15. set_time_limit(0);
  16. // 执行命令,并将输出保存到变量中
  17. $descriptorspec = array(
  18. 0 => array("pipe", "r"), // 标准输入,我们不需要
  19. 1 => array("pipe", "w"), // 标准输出,我们需要将其捕获
  20. 2 => array("pipe", "w") // 标准错误,我们也需要将其捕获
  21. );
  22. $process = proc_open($command, $descriptorspec, $pipes, $cwd);
  23. // 检查进程是否成功创建
  24. if (!is_resource($process)) {
  25. return "Could not execute command: $command";
  26. }
  27. // 从管道中获取命令的输出
  28. $output = '';
  29. while (!feof($pipes[1])) {
  30. $output .= fgets($pipes[1]);
  31. }
  32. while (!feof($pipes[2])) {
  33. $output .= fgets($pipes[2]);
  34. }
  35. // 关闭管道和进程
  36. fclose($pipes[0]);
  37. fclose($pipes[1]);
  38. fclose($pipes[2]);
  39. $status = proc_close($process);
  40. // 判断命令的执行结果
  41. if ($status === 0) {
  42. return str_contains($output, 'Command failed') ? $output : true;
  43. } else {
  44. return $output;
  45. }
  46. }
  47. }