【问题标题】:PHP/HTTP-API - how to call different PHP files from extern?PHP/HTTP-API - 如何从外部调用不同的 PHP 文件?
【发布时间】:2017-08-31 12:42:55
【问题描述】:

我正在构建一个非常简单的 PHP API,它可以响应 HTTP 请求。它应该能够创建一个用户并删除一个。所以目前有两个 PHP 文件/类。一种用于删除,一种用于创建/插入用户。

我的问题:

我需要如何调用它们(URL 看起来如何)?正如我在一些示例中看到的,大多数人只通过路径调用它们:

删除:http://example.org/deletehttp://example.org/delete.php

创建:http://exmple.org/createhttp://example.org/create.php

那么,我必须创建这些路径吗?我需要将所有文件重命名为 index.php 并将它们放到正确的路径吗?

我需要知道,什么是已建立的实践(我使用 php Storm IDE)。

谢谢。

【问题讨论】:

  • 使用路由器。
  • 当然 - 我的意思是,如果我在最后使用 .php 调用它会出错 - 我从 java 发出 http 请求。

标签: php api http


【解决方案1】:

对此有不同的方法可用...

网址重写

在您的 .htaccess 中(如果您没有此文件,则在您的根文件夹中创建它)并将其复制到:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L]

然后调用http://example.org/create,会改写为http://example.org/index.php?page=create

如果你想保留两个不同的页面(create.php 和 delete.php),那么更喜欢这个:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ $1.php [L]

因此,对于第二个变体 http://example.org/create,将调用 http://example.org/create.php 而不是 index.php?page=create

子文件夹

我喜欢这个解决方案,因为它使您的 API 源代码结构化。因此,像这样在每个子文件夹中创建一些带有 index.php 的子文件夹:

/_include
    -- config.php
    -- other scripts to include...
/create
    -- index.php
/delete
    -- index.php

所以用户会打电话给http://example.org/createhttp://example.org/delete!您可以使用两个 index.php 调用的脚本创建一个 _include 文件夹。

【讨论】:

  • 好的,拥有多个 index.php 有点令人困惑 - 但它似乎是合法的。谢谢
【解决方案2】:

您需要将您的 URL 指向您的 PHP 文件或路由的位置。例如,如果您将其指向 http://example.com/delete,则需要确保存在该路径。

将您的 URL 指向 http://example.com/delete.php 只要它存在就可以正常工作。

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 2016-11-29
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多