Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP REST put/delete options

Tags:

rest

php

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?

like image 700
abiku Avatar asked Aug 23 '12 06:08

abiku


1 Answers

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.

<form method="post" action="my_resource.php">
  ...
  <input type="hidden" name="REQUEST_METHOD" value="PUT" />
<form>

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:

/* my_resource.php */

$method = strtolower($_SERVER['REQUEST_METHOD']);
if( $method === 'post' && isset($_REQUEST['REQUEST_METHOD'])) {
    $tmp = strtolower((string)$_REQUEST['REQUEST_METHOD']);
    if( in_array( $tmp, array( 'put', 'delete', 'head', 'options' ))) {
        $method = $tmp;
    }
    unset($tmp);
}

// now, just run the logic that's appropriate for the requested method
switch( $method ) {
    case "get":
        // logic for GET here
        break;

    case "put":
        // logic for PUT here
        break;        

    case "post":
        // logic for POST here
        break;

    case "delete":
        // logic for DELETE here
        break;

    case "head":
        // logic for DELETE here
        break;

    case "options":
        // logic for DELETE here
        break;

    default:
        header('HTTP/1.0 501 Not Implemented');
        die();
}

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:

<button onclick="doSave()">Save</button>

<script>
    var myObject = {
       // ... some object properties that 
       // that you'll eventually want to save ...
    };

    function doSave() {
        var xhr = createxmlhttprequest();

        // initialize the request by specifying the method 
        // (ie: "get", "put", "post", "delete", etc.), and the
        // url (in this case, "my_resource.php").  The last param
        // should always be `true`.

        xhr.open("put", "my_resource.php", true);
        xhr.setRequestHeader('Content-Type', 'application/json');

        xhr.onreadystatechange = function() {
           if (xhr.readystate != 4) { return; }
           var serverresponse = xhr.responsetext;

           // ... this code runs when the response comes back
           // from the server.  you'll have to check for success
           // and handle the response document (if any).
        };

        // this initiates the request, sending the contents
        // of `myObject` as a JSON string.  

        xhr.send(JSON.stringify(myObject));

        // The request runs in the background
        // The `onreadystatechange` function above
        // detects and handles the completed response.
    }
</script>

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

like image 186
Lee Avatar answered Sep 18 '22 11:09

Lee