让网页执行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;
    }
}
相关推荐
damoluomu1 天前
挑 PHP CMS 之前,先学会看它的协议
php
子非鱼a2 天前
【WEB】Online ToolWEB
php
PHP实战开发录2 天前
Nginx上传大文件为什么报413
nginx·php·开发
damoluomu2 天前
国产企业级 PHP CMS:哪些能免费商用
php
郑州光合科技余经理2 天前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
MyFreeIT2 天前
Android PHP Manual
php
aixingpan2 天前
aixingpan.cn API开发文档:api_docs_trichart_natal_progression_sec_transit2接口指南
前端·php
sbjdhjd3 天前
从日志包含到临时文件竞争:文件包含进阶复盘中的 Docker、Windows 与 Session 限制
网络·安全·web安全·网络安全·数据挖掘·php·rce
daxiangxm3 天前
【趣味休息】“围住小猫在线玩”-“困住小猫”,又回来了
数据结构·人工智能·vscode·github·php
星光开发者3 天前
基于Spring Boot的充电桩管理系统的设计与实现-计算机毕设【课程设计】57105
vue.js·spring boot·vscode·mysql·django·php·express