PHP에서 PUT / DELETE 인수 처리
CodeIgniter 용 REST 클라이언트 라이브러리에서 작업 중이며 PHP에서 PUT 및 DELETE 인수를 보내는 방법을 찾기 위해 고군분투하고 있습니다.
몇 곳에서 사람들이 옵션을 사용하는 것을 보았습니다.
$this->option(CURLOPT_PUT, TRUE);
$this->option(CURLOPT_POSTFIELDS, $params);
짜증나게도 이것은 아무 일도하지 않는 것 같습니다. 이것이 PUT 매개 변수를 설정하는 올바른 방법입니까?
그렇다면 DELETE 매개 변수를 어떻게 설정합니까?
$ this-> option ()은 내 라이브러리의 일부이며, 단순히 CURLOPT_XX 상수의 배열을 구축하고 구축 된 cURL 요청이 실행될 때 curl_setopt_array ()로 보냅니다.
다음 코드를 사용하여 PUT 및 DELETE 매개 변수를 읽으려고합니다.
case 'put':
// Set up out PUT variables
parse_str(file_get_contents('php://input'), $this->_put_args);
break;
case 'delete':
// Set up out PUT variables
parse_str(file_get_contents('php://input'), $this->_delete_args);
break;
여기에는 두 가지 옵션이 있습니다. 잘못된 방식으로 접근하고 있거나 라이브러리 어딘가에 버그가 있습니다. 이것이 이론적으로 작동하는지 알려 주시면 해결할 때까지 디버그를 망치면됩니다.
근본적으로 잘못된 접근 방식에 더 이상 시간을 낭비하고 싶지 않습니다.
대신 사용의 CURLOPT_PUT = TRUE
사용 CURLOPT_CUSTOMREQUEST = 'PUT'
과 CURLOPT_CUSTOMREQUEST = 'DELETE'
함께 다음 바로 설정 값을 CURLOPT_POSTFIELDS
.
다음은 PUT 및 DELETE 매개 변수를 처리하려는 다른 사용자에게 도움이 될 수있는 몇 가지 코드입니다. 당신은 설정할 수 있습니다 $_PUT
및 $_DELETE
경유 $GLOBALS[]
하지만, 선언하지 않는 한 그들은 기능에 직접 액세스 할 수 없습니다 global
또는 통해 액세스 $GLOBALS[]
. 이 문제를 해결하기 위해 GET / POST / PUT / DELETE 요청 인수를 읽는 간단한 클래스를 만들었습니다. 이것은 또한 $_REQUEST
PUT / DELETE 매개 변수로 채워집니다 .
이 클래스는 PUT / DELETE 매개 변수를 구문 분석하고 GET / POST도 지원합니다.
class Params {
private $params = Array();
public function __construct() {
$this->_parseParams();
}
/**
* @brief Lookup request params
* @param string $name Name of the argument to lookup
* @param mixed $default Default value to return if argument is missing
* @returns The value from the GET/POST/PUT/DELETE value, or $default if not set
*/
public function get($name, $default = null) {
if (isset($this->params[$name])) {
return $this->params[$name];
} else {
return $default;
}
}
private function _parseParams() {
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "PUT" || $method == "DELETE") {
parse_str(file_get_contents('php://input'), $this->params);
$GLOBALS["_{$method}"] = $this->params;
// Add these request vars into _REQUEST, mimicing default behavior, PUT/DELETE will override existing COOKIE/GET vars
$_REQUEST = $this->params + $_REQUEST;
} else if ($method == "GET") {
$this->params = $_GET;
} else if ($method == "POST") {
$this->params = $_POST;
}
}
}
Just remember, most webservers do not handle PUT & DELETE requests. Since you're making a library, I'd suggest thinking about accounting for this. Typically, there are two conventions you can use to mimic PUT & DELETE via POST.
- use a custom POST variable (ex. _METHOD=PUT) which overrides POST
- set a custom HTTP header (ex. X-HTTP-Method-Override: PUT)
Generally speaking, most RESTful services that don't allow PUT & DELETE directly will support at least one of those strategies. You can use cURL to set a custom header if you need via the CURLOPT_HTTPHEADER
option.
// ex...
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT') );
I think you're mixing your verbs - PUT is for putting a file, POST is for posting variables (although you can POST a file).
To set the post variables, use CURLOPT_POSTFIELDS
with either a string of param1=val1¶m2=val2
or an associative array.
To do a DELETE, you'll want to use the curl option CURLOPT_CUSTOMREQUEST
This is how i sole my DELETE problem:
==>> in REST_Controller.php i replace the delault _parse_delete() function by :
protected function _parse_delete()
{
$this->_delete_args = $_DELETE;
$this->request->format and $this->request->body = file_get_contents('php://input');
// Set up out DELETE variables (which shouldn't really exist, but sssh!)
parse_str(file_get_contents('php://input'), $this->_delete_args);
}
;) it works for me!
This is my version of the DELETE for CI. It accepts GET-style arguments for the DELETE, even same name arguments, i.e.: GET /some/url?id=1&id=2&id=3
protected function _parse_delete()
{
$query = $_SERVER['QUERY_STRING'];
if ( !empty( $query ) )
{
foreach( explode('&', $query ) as $param )
{
list($k, $v) = explode('=', $param);
$k = urldecode($k);
$v = urldecode($v);
if ( isset( $this->_delete_args[$k] ) )
{
if ( is_scalar( $this->_delete_args[$k] ) )
{
$this->_delete_args[$k] = array( $this->_delete_args[$k] );
}
$this->_delete_args[$k][] = $v ;
}
else
{
$this->_delete_args[$k] = $v;
}
}
}
}
참고URL : https://stackoverflow.com/questions/2081894/handling-put-delete-arguments-in-php
'programing tip' 카테고리의 다른 글
jQuery를 사용하여 JavaScript 객체에서 항목 추가 / 제거 (0) | 2020.09.23 |
---|---|
iPhone 앱을위한 기성 캘린더 컨트롤이 있습니까? (0) | 2020.09.22 |
뷰티플 스프로 속성 값 추출 (0) | 2020.09.22 |
new Date ()는 Chrome에서 작동하지만 Firefox에서는 작동하지 않습니다. (0) | 2020.09.22 |
수업이나 사전을 사용해야합니까? (0) | 2020.09.22 |