首页 > 解决方案 > php://input 将 url 更改为不包含 index.php 时丢失数据

问题描述

因此,我正在构建一个自定义 API 端点,我需要将数据从 Laravel 发送到该端点。我需要大量的 URL,并希望尽可能干净地做到这一点,同时仍然必须在没有框架的情况下从头开始。

我试图创建以下端点

/api/类别/创建/

现在,我可以使用 Guzzle 发布到 /api/categories/create/index.php 并获得内容file_get_contents('php://input')就好了。而且我知道当我删除 index.php 时,它仍然会发布到正确的位置,因为我可以将“你好”作为响应发回并且我确实收到了。`

对于为什么file_get_contents('php://input')可以获取我正在发送的数据,但只有当我在 url 末尾明确指定 index.php 时,我感到有些困惑。

这是我的要求,虽然我不认为错误来自这个......

$client = new Client([
    'base_uri' => 'http://example.test/'
]);

$course = [
    'title'       => $request->title,
    'description' => $request->description,
    'site'        => $request->site
];

$response = $client->post('api/categories/create', [
    'json' => ['course' => $course]
]);

有任何想法吗?

标签: phplaravelapi-design

解决方案


您需要添加一个.htaccess文件,该文件定义index.php为单点访问。

重写模式应该是(类似于)controller/method/id,例如:

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /

    # remove trailing slash
    RewriteRule ^(.*)\/(\?.*)?$ $1$2 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/(.*)/(\d+)$ /index.php?controller=$1&method=$2&id=$3 [L,NC,QSA]

</IfModule>

其次是更多的模式,它们在没有id和没有的情况下重写method(默认为索引)。

api/categories/create需要类似的模式 ~ ^(.*)/(.*)/(.*)$ /index.php?controller=$1&subject=$2&method=$3 [L,NC,QSA]。也可以用逻辑ORalike定义可能的值^(.*)/(.*)/(create|read|update|destroy)(/|)$


推荐阅读