In web development, RESTful APIs are commonly used for client-server communication. PUT requests are generally used to update existing resources. This article explains the key steps to handle PUT requests in PHP and provides concrete code examples to help you master this skill quickly.
PUT requests are used to replace the complete representation of a resource. Unlike POST requests which may partially update a resource, PUT requires the client to send the full new content of the resource, which the server then replaces the original resource with. Therefore, when handling a PUT request, it is important to accurately receive and save all data sent by the client.
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
http_response_code(405);
echo json_encode(['error' => 'Invalid request method']);
exit();
}
<p>$requestData = json_decode(file_get_contents('php://input'), true);<br>
if ($requestData === null) {<br>
http_response_code(400);<br>
echo json_encode(['error' => 'Invalid request data']);<br>
exit();<br>
}</p>
<p>$result = updateResource($requestData);<br>
if ($result === false) {<br>
http_response_code(500);<br>
echo json_encode(['error' => 'Error updating resource']);<br>
exit();<br>
}</p>
<p>http_response_code(200);<br>
echo json_encode(['message' => 'Resource updated successfully']);</p>
<p>function updateResource($data)<br>
{<br>
// Perform update operation here, e.g. writing data to the database<br>
// ...</p>
}
By following these steps, you can implement a simple and practical PUT request handler. The key is to validate the request method, properly parse input data, execute update logic, and return appropriate responses. Depending on your needs, you can further extend the implementation with data validation, error handling, and security measures to build a more robust RESTful API.