Trying to understand the REST method of creating apps in PHP.
I’m having a problem in understanding how to send put/delete from php script.
In the internet I can only find how to determine which php method has been sent.
if($_SERVER['REQUEST_METHOD'] == 'DELETE')
But how to send this DELETE method?
Normaly what I do when want to delete some record from DB i have normal html form with method set to post/get and record db id then I press submit button to send post/get form.
How to create this submit to send delete/put methods?
There are two common ways to send a request from an HTML page, using an http method other than GET or POST.
#1: use an html form to send a POST request, but include a hidden form field that tells the server to treat the request as though it were using a different method. This is the approach outlined by @xdazz.
In your PHP script,
"my_resource.php", you’ll have to look at both the real request method, and the submitted form field, to determine which logic to invoke:Note: you can put the above logic into each page (or call it from each page). An alternative is to build a proxy script, (eg.
"rest-form-proxy.php"). Then, all forms in your site will submit to the proxy, including a request_method, and a target url. The proxy will extract the provided information, and forward the request on to the desired url using the proper requested http method.The proxy approach is a great alternative to embedding the logic in each script. If you do build the proxy though, be sure to check the requested URL, and dis-allow any url that doesn’t point back to your own site. Failure to do this check will allow others to use your proxy to launch malicious attacks on other websites; and it could also compromise security and/or privacy on your website.
—
#2: Use Javascript, in your HTML page, to initiate an XMLHttpRequest. This is a more complex approach, which requires a bit of javascript, but it can be more flexible in some cases. It allows you to send requests to the server without re-loading the page. It also allows you to send data in many different formats (you are not limited to sending only data from an html form). For example:
There’s a lot more to XMLHttpRequest than I’ve shown in the basic example above. If you choose this route, please research it thoroughly. Among other things, make sure you handle the various error conditions properly. There are also a number of issues with cross-browser compatibility, many of which can be addressed by using an intermediary, like jQuery’s $.ajax() function.
Finally, I should note that the two methods above are not mutually exclusive. It’s quite possible to use forms for some requests, and XMLHttpRequest for others, as long as you build your server so that it can handle either kind of request (as shown in #1 above).