如何在 Apache2 和 PHP 中启用和使用 HTTP PUT 和 DELETE? [英] How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

查看:32
本文介绍了如何在 Apache2 和 PHP 中启用和使用 HTTP PUT 和 DELETE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该就是这么简单.我遵循了我能找到的每个教程和论坛,但我无法让它工作.我只是想在 Apache2 上用 PHP 构建一个 RESTful API.

It should be so simple. I've followed every tutorial and forum I could find, yet I can't get it to work. I simply want to build a RESTful API in PHP on Apache2.

在我的 VirtualHost 指令中,我说:

In my VirtualHost directive I say:

<Directory />
    AllowOverride All
    <Limit GET HEAD POST PUT DELETE OPTIONS>
        Order Allow,Deny
        Allow from all
    </Limit>
</Directory>

然而,我向服务器发出的每个 PUT 请求都得到不支持的 405 方法.

Yet every PUT request I make to the server, I get 405 method not supported.

有人提倡使用 Script 指令,但由于我使用的是 mod_php,而不是 CGI,我不明白为什么会这样.

Someone advocated using the Script directive, but since I use mod_php, as opposed to CGI, I don't see why that would work.

人们提到使用 WebDAV,但对我来说这似乎有点矫枉过正.毕竟,我不需要 DAV 锁定、DAV 文件系统等.我想做的就是将请求传递给 PHP 脚本并自己处理所有事情.我只想为干净的语义启用 PUT 和 DELETE.

People mention using WebDAV, but to me that seems like overkill. After all, I don't need DAV locking, a DAV filesystem, etc. All I want to do is pass the request on to a PHP script and handle everything myself. I only want to enable PUT and DELETE for the clean semantics.

推荐答案

您不需要配置任何东西.只需确保请求映射到您的 PHP 文件并使用带有路径信息的请求.例如,如果您在根目录中有一个名为 handler.php 的文件,其中包含以下内容:

You don't need to configure anything. Just make sure that the requests map to your PHP file and use requests with path info. For example, if you have in the root a file named handler.php with this content:

<?php

var_dump($_SERVER['REQUEST_METHOD']);
var_dump($_SERVER['REQUEST_URI']);
var_dump($_SERVER['PATH_INFO']);

if (($stream = fopen('php://input', "r")) !== FALSE)
    var_dump(stream_get_contents($stream));

以下 HTTP 请求将起作用:

The following HTTP request would work:

Established connection with 127.0.0.1 on port 81
PUT /handler.php/bla/foo HTTP/1.1
Host: localhost:81
Content-length: 5
 
boo
HTTP/1.1 200 OK
Date: Sat, 29 May 2010 16:00:20 GMT
Server: Apache/2.2.13 (Win32) PHP/5.3.0
X-Powered-By: PHP/5.3.0
Content-Length: 89
Content-Type: text/html
 
string(3) "PUT"
string(20) "/handler.php/bla/foo"
string(8) "/bla/foo"
string(5) "boo
"
Connection closed remotely.

您可以使用 MultiViews 或您可以使用 mod_rewrite 使 URL 完全合乎逻辑.

You can hide the "php" extension with MultiViews or you can make URLs completely logical with mod_rewrite.

另请参阅 AcceptPathInfo 指令的文档和这个问题是关于如何在 enctype 为 multipart/form-data使 PHP 不解析 POST 数据.

See also the documentation for the AcceptPathInfo directive and this question on how to make PHP not parse POST data when enctype is multipart/form-data.

这篇关于如何在 Apache2 和 PHP 中启用和使用 HTTP PUT 和 DELETE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆