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

PHP内置web服务运行时$_GET['url']判断失效问题求助

问题原因

你当前的代码逻辑依赖$_GET['url']参数获取请求路径,但PHP内置服务器默认不会自动将/exchange这类路径格式转换为$_GET['url']参数,因此isset($_GET['url'])判断始终不成立,直接进入error 1的返回分支。

解决方案

你可以任选以下两种方案之一解决:

方案1:不修改现有业务代码,新增路由启动脚本

  1. 项目根目录新建router.php文件,写入以下代码:
<?php
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
// 静态资源直接返回
if ($uri !== '/' && file_exists(__DIR__ . $uri)) {
    return false;
}
// 将路径赋值给$_GET['url']参数,兼容原有逻辑
$_GET['url'] = ltrim($uri, '/');
require __DIR__ . '/index.php';
  1. 替换启动命令为:
php -S localhost:8000 router.php

启动后原有逻辑即可正常运行。

方案2:修改代码适配所有运行环境

直接从请求全局变量中提取路径,不需要依赖$_GET['url']参数,修改后的代码逻辑如下:

<?php
/**
 * Back-end Challenge.
 *
 * PHP version 7.2
 *
 * Este será o arquivo chamado na execução dos testes automátizados.
 *
 * @category Challenge
 * @package  Back-end
 * @author   Seu Nome <seu-email@seu-provedor.com>
 * @license  http://opensource.org/licenses/MIT MIT
 * @link     https://github.com/apiki/back-end-challenge
 */

declare(strict_types=1);

header('Content-Type: application/json');

require __DIR__ . '/vendor/autoload.php';

// 替换原有isset($_GET['url'])判断逻辑
$rawPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$url = explode('/', ltrim($rawPath, '/'));
if (!empty($url[0])) {
    if ($url[0] === "exchange") {
        $service = 'App\Services\\'.ucfirst($url[0]).'Service';
        array_shift($url);
        if(isset($url[0]) && is_numeric($url[0])){
            $method = strtolower($_SERVER['REQUEST_METHOD']);
            try {
                $response = call_user_func(array(new $service, $method), $url);

                
                if($response == "error"){
                    http_response_code(400);
                    echo json_encode(array('status' => 'error 5'));  
                }else{
                    http_response_code(200);
                    echo json_encode(array('valorConvertido' => $response->getValor(), 'simboloMoeda' => $response->getSimbolo()));
                }
                exit;
            } catch (\Exception $e) {
                http_response_code(400);
                echo json_encode(array('status' => 'error 4', 'data' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
                exit;
            }
        }else{ 
            http_response_code(400);
            echo json_encode(array('status' => 'error 3'));  
            exit;
        }
    }else{
        http_response_code(400);
        echo json_encode(array('status' => 'error 2'));  
        exit;
    }
}else{
    http_response_code(400);
    echo json_encode(array('status' => 'error 1'));
    exit;
}

该方案同时兼容PHP内置服务器、Apache、Nginx等多种运行环境。

额外提示:原代码中ucfirst($url[0]);没有赋值给变量,属于无效代码,可以直接删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:36:03