我正在构建一个非常简单的 PHP API,它可以响应 HTTP 请求。它应该能够创建一个用户并删除一个。所以目前有两个 PHP 文件/类。一种用于删除,一种用于创建/插入用户。
我的问题:
我需要如何调用它们(URL 看起来如何)?正如我在一些例子中看到的,大多数人只通过路径调用它们:
删除:http://example.org/delete
或 http://example.org/delete.php
创建:http://example.org/create
或 http://example.org/create.php
那么,我必须创建这些路径吗?我是否需要将所有文件重命名为 index.php 并将它们放在正确的路径中?
我需要知道什么是已建立的实践(我使用 php storm IDE)。
谢谢。
最佳答案
可以使用不同的方法...
url重写
在您的 .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/create和 http://example.org/delete !您可以使用 index.php 调用的脚本创建一个 _include 文件夹。
关于PHP/HTTP-API - 如何从外部调用不同的 PHP 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45981745/