How do I send a PUT/DELETE request in HTML?

2019-04-19 20:27发布

问题:

I'm messing around with REST in PHP and I understand that I can capture the request method vi a $_SERVER['REQUEST_METHOD']. But how do I trigger PUT/DELETE requests in PHP without the use of cURL? I want to use the features of a default PHP installation to do this. I can't imagine changing the method attribute of the form tag to specify a method other than GET or POST would work on all browsers...plus the HTML standard doesn't recognize it.

I'm on PHP 5.2.6, by the way.

Thanks.

回答1:

Usually this is done by a hidden form field, and handled in the application (not the webserver, by and large).

<input type="hidden" name="_method" value="put" />

So in this case you'd use a simple set of if-else statements to determine if the _method variable is overridden (validly, of course). I'd use something like:

$method = 'get';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
  if(isset($_POST['_method']
     && ($_POST['_method'] == 'PUT' || $_POST['_method'] == 'DELETE')) {
    $method = strtolower($_POST['_method']);
  } else {
    $method = 'post';
  }
}

This would be a simple way to determine the request type for your application or framework.



回答2:

fopen will do HTTP, but I believe it will only do GET requests. If you use fsockopen, you'll need to handle the HTTP protocol yourself, generating headers, etc..

You can use HTTPRequest (in the php_http extension) or PEAR.

Update:

If you're really talking about making PUT/DELETE requests to your PHP scripts, rather than from them, this question may be of interest:

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?



回答3:

If you want to use PHP's built-in functions, but not cURL, you're pretty much stuck with fsockopen(), etc.,

or at best, a library built around those functions, like Snoopy



回答4:

You may want to take a look at WebDav (PHP WebDav slide show). It's built to PUSH, DELETE, Etc... Of course the server you are targeting needs to accept PUSH's and DELETE's which would mean Apache is using mod_webdav or something similar. Otherwise a lower-level solution will be required (as others have indicated)



标签: rest