Unblocking PUT and DELETE in Apache2 with mod_php
Building a RESTful API often hits an immediate wall: you can GET and POST just fine, but every attempt to PUT or DELETE results in a 405 Method Not Allowed. This is frustrating because the underlying issue is frequently misconfigured web server directives rather than a flaw in your PHP logic.
The core problem lies in how Apache2 handles method restrictions by default. When you switch from the standard mod_cgi to mod_php, Apache treats requests differently regarding which methods are permitted at the directory level. By default, Apache allows GET and POST for file-based resources but restricts others unless explicitly told otherwise.
The configuration snippet you likely found online uses the <Limit> directive with Order Allow,Deny. While this syntax works in older Apache versions (2.4 and earlier), modern setups often behave differently or require a specific approach depending on the version of Apache you are running.
If you are using Apache 2.4 (which is standard for most Linux distributions today), the Order directive is deprecated, though it usually still functions. However, the critical factor is ensuring that the <Directory> block actually encompasses your application root or that you have specific overrides enabled for your virtual host.
The Correct Configuration Approach
To enable PUT and DELETE globally for your server, you need to adjust the access control rules. Here is a robust way to configure this in your VirtualHost or main configuration file:
<Directory /var/www/html>
AllowOverride All
# Explicitly allow the methods we need
<LimitExcept GET POST HEAD OPTIONS TRACE>
Require all granted
</LimitExcept>
</Directory>
Note the shift from Order Allow,Deny to Require. If you must stick to the older syntax found in some tutorials, ensure your Apache version supports it. The logic remains: explicitly deny everything first, then allow the specific methods you require (GET, POST, PUT, DELETE), or conversely, allow everything except the dangerous ones if security is a concern.
Why mod_php Matters
You might wonder why the Script directive suggestion doesn't apply here. The Script directive controls which handler processes the request based on its URI mapping. Since you are using mod_php, your PHP scripts are handled directly by the Apache process via mod_php7 (or mod_php5). There is no CGI wrapper involved.
When you send a PUT request to a .php file, Apache checks the method restrictions before it even considers which module should handle the script. If the <Limit> block disallows PUT, Apache returns 405 immediately, bypassing your PHP code entirely. Your PHP script never sees the request; the web server rejects it at the ingress level.
Implementing in PHP
Once the Apache configuration allows these methods, handling them in PHP is straightforward. You can inspect $_SERVER['REQUEST_METHOD'] to determine the action and manipulate the database accordingly.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
// Handle update logic
$id = $_GET['id'];
$data = json_decode(file_get_contents('php://input'), true);
// Validate $id and $data before updating the database
if (!empty($id)) {
// Update query here
echo json_encode(['status' => 'success', 'message' => 'Resource updated']);
} else {
http_response_code(400);
echo json_encode(['error' => 'Missing ID parameter']);
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// Handle delete logic
$id = $_GET['id'];
if (!empty($id)) {
// Delete query here
echo json_encode(['status' => 'success', 'message' => 'Resource deleted']);
} else {
http_response_code(400);
echo json_encode(['error' => 'Missing ID parameter']);
}
} else {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
}
?>
Trade-offs and Common Pitfalls
A common mistake is relying solely on .htaccess files to enable these methods. While AllowOverride All permits directives in .htaccess, it is generally more performant and cleaner to handle method restrictions in the main server configuration or VirtualHost file. Modifying the global config ensures consistency across your entire site rather than relying on scattered .htaccess rules that might conflict with other modules like rewrite or security headers.
Another consideration is CORS (Cross-Origin Resource Sharing). Enabling PUT and DELETE opens the door for clients to modify server state from different domains. Ensure your PHP scripts validate origins if you are serving a frontend from a different domain, regardless of whether the request originates from the same origin.
If you prefer a framework abstraction over raw Apache configuration checks, tools like LaravelCompany provide robust scaffolding for RESTful APIs where these HTTP methods are handled elegantly by the framework's routing and controller mechanisms, abstracting much of the manual HTTP verb handling away from your core logic.