I am building a rest webservice using SLIM which is working fine with GET and POST method but when i tried to Request a PUT method. It is giving me error “405 Method Not Allowed”. i don’t know what is the problem.
Here is my code: $app->put('/user/:id', function($user_id) use ($app) { echo 'done'; });
Here is my .htaccess: RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L]
Thanks for response. Can you please write a single example here?
e.g: $app->put('/user/:id', function($user_id) use ($app) { echo 'done'; });
so that it would make me more clear.
Here is an example for the route that matches your PUT request:
$app->put('/user/{user_id}', function($request, $response, $args) {
// the url argument is stored in $args
$userId = $args['user_id'];
// parsing the form data
$data = $request->getParsedBody();
$name = $data['name'];
// writing a string as output, normally you would some sort of view
$response->getBody()->write(
sprintf('PUT: user id=%d, name=%s', $userId, htmlspecialchars($name))
);
});
You can submit a request that matches the PUT route using a POST request, by adding _METHOD=PUT in your post data, as I mentioned. Using an HTML form this would look something like:
<form action="/user/5" method="POST">
<-- indication for Slim that this should be interpreted as a PUT request -->
<input type="hidden" name="_METHOD" value="PUT"/>
<!-- more form data -->
<p><label>Name:</label> <input type="text" name="name"/></p>
<p><button type="submit">Submit form</button></p>
</form>
Sorry @JoeBengalen Without using SLIM, I can update a column with simple Query. But Slim “PUT” method is not working and I am continuously getting Method Not Allowed Error. Need Help!
$app->put('/user/:id', function($name) use ($app)
{
global $app;
verifyRequiredParams(array('id'));
$id= $app->request->put('id');
$db = new DbHandler();
$response = $db->updUser($id, $name);
echoRespnse(200, $response);
});
And in DbHandler() function, I am doing this:
public function updUser($id, $name)
{
$response = array();
$db = new DbConnect();
$conn = $db->connect();
$sql = "UPDATE table SET name = ? WHERE id = ?";
$stmt = sqlsrv_prepare( $conn, $sql, array( &$name, &$id));
if (sqlsrv_execute( $stmt ) === true)
{
// User successfully updated
$response["error"] = false;
$response["message"] = 'updated success';
}
else
{
// Failed to update user
$response["error"] = true;
$response["message"] = "Failed to update ";
}
return $response;
}
But whenever I access this function, it returns me 405 Method Not Allowed Error.
If I do POST requests, or GET request with the same methods, then all works fine!