Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

Tags:

rest

php

apache

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.

In my VirtualHost directive I say:

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

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

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

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.

like image 557
Andreas Jansson Avatar asked May 29 '10 09:05

Andreas Jansson


People also ask

How do you enable put and delete methods in Apache?

The short answer: You need to enable mod_actions and mod_rewrite in Apache, add a <Limit> and <LimitExcept> block to your <Directory> block, and set up a RewriteCond %{REQUEST_METHOD} (PUT|DELETE) and a RewriteRule .


1 Answers

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)); 

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. 

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

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.

like image 101
Artefacto Avatar answered Sep 29 '22 03:09

Artefacto