让网页执行cmd命令

网页如何执行cmd命令,看似不能。其实现在已经可以了。

几个关键的要点。前端异步投递任务。php执行任务并返回结果给前端。

复制代码
<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;

/**
 * Claude 命令 - 通过 proc_open 执行 claude CLI
 */
class ClaudeCmd extends Command
{
    protected function configure(): void
    {
        $this->setName('cmd')
            ->setDescription('通过 proc_open 执行 claude CLI 命令')
            ->addArgument('claude-args', Argument::OPTIONAL, '传递给 claude 的参数')
            ->addOption('dir', 'd', Option::VALUE_OPTIONAL, '指定工作目录', 'D:/code/tp8/tp8');
    }

    protected function execute(Input $input, Output $output): int
    {

        $claudeArgs = $input->getArgument('claude-args') ?: 'dir';

        $descriptors = [
            0 => ['pipe', 'r'],  // stdin
            1 => ['pipe', 'w'],  // stdout
            2 => ['pipe', 'w'],  // stderr
        ];

        $pipes = [];


        $output->writeln('执行: ' . $claudeArgs);

        $proc = proc_open(
             $claudeArgs,
            $descriptors,
            $pipes
        );

        if (!is_resource($proc)) {
            $output->writeln('<error>无法启动进程</error>');
            return 1;
        }

        // 关闭 stdin
        fclose($pipes[0]);

        // 读取输出
        $stdout = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        $stderr = stream_get_contents($pipes[2]);
        fclose($pipes[2]);

        $exitCode = proc_close($proc);

        if (!empty($stderr)) {
            $output->writeln('<error>STDERR:</error>');
            $output->writeln($stderr);
        }

        if (!empty($stdout)) {
            $output->writeln('<info>STDOUT:</info>');
            $output->writeln($stdout);
        }

        $output->writeln('<info>退出码: ' . $exitCode . '</info>');

        return $exitCode;
    }
}
相关推荐
甲骨文数据库10 小时前
caddy配合PHP(http模式)
php
啊阿狸不会拉杆10 小时前
《计算机网络-自顶向下方法》1.7 计算机网络和因特网的历史 读书笔记
计算机网络·php·perl
智塑未来13 小时前
常用的在线ping测试工具有哪些
服务器·开发语言·php
啊阿狸不会拉杆13 小时前
《计算机网络-自顶向下方法》1.3 网络核心 读书笔记
网络·人工智能·计算机网络·ai·php
171320330计算机毕设编程14 小时前
2027计算机毕设五大方向对比&选题推荐
java·ide·python·算法·django·php·推荐算法
IT小白杨15 小时前
TikTok小店防封号浏览器实战:2026年多店铺环境隔离与账号安全运营技术解析
开发语言·数据库·安全·php·chrome devtools·指纹浏览器
catchadmin16 小时前
免费可商用 PHP 管理后台 CatchAdmin V5.4.0 发布,新增短信服务能力
开发语言·php
Tanshu_API君16 小时前
身份证实名认证接口对接:PHP 接入二要素核验实战
php·api·实名认证·身份证实名认证·身份认证接口·运营商接口·运营商二要素
啊阿狸不会拉杆17 小时前
《计算机网络-自顶向下方法》1.5 协议层次及其服务模型 读书笔记
开发语言·计算机网络·php
斑马13917 小时前
Linux软件编程学习笔记(十)——网络(二)——TCP通信
开发语言·网络·php