PHP CURL DELETE 요청


100

PHP와 cURL을 사용하여 DELETE http 요청을 수행하려고합니다.

나는 그것을하는 방법을 여러 곳에서 읽었지만 아무것도 나를 위해 일하지 않는 것 같습니다.

이것이 내가하는 방법입니다.

public function curl_req($path,$json,$req)
{
    $ch = curl_init($this->__url.$path);
    $data = json_encode($json);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data)));
    $result = curl_exec($ch);
    $result = json_decode($result);
    return $result;
}

그런 다음 계속해서 내 기능을 사용합니다.

public function deleteUser($extid)
{
    $path = "/rest/user/".$extid."/;token=".$this->__token;
    $result = $this->curl_req($path,"","DELETE");
    return $result;

}

이것은 나에게 HTTP 내부 서버 오류를 제공합니다. GET 및 POST와 함께 동일한 curl_req 메서드를 사용하는 다른 기능에서는 모든 것이 잘 진행됩니다.

그래서 내가 뭘 잘못하고 있니?


3
내부 서버 오류는 요청을 수신하는 스크립트에 문제가 있음을 의미합니다.
— Brad

감사합니다 Brad-알아요, DELETE 요청으로 보내지 않기 때문에 그거 같아요. Firefox 용 REST 클라이언트 플러그인을 사용하고 DELETE로 똑같은 요청을 보내면 제대로 작동합니다. 따라서 cURL과 같은 이음새가 요청을 DELETE로 보내지 않습니다.
— Bolli 2011


마크 고마워요하지만 그가 나랑 똑같은 일을하는 것 같나요? PHP로 DELETE 요청을 보내는 것이 불가능합니까? cURL이없는 다른 방법이 있다면 저도 사용할 수 있습니다.
— Bolli 2011

답변:


216

나는 마침내 이것을 스스로 해결했다. 다른 사람이이 문제를 겪고 있다면 내 해결책은 다음과 같습니다.

새로운 방법을 만들었습니다.

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

업데이트 2

이것은 일부 사람들에게 도움이되는 것 같기 때문에 JSON 디코딩 된 객체에서 HTTP 응답을 반환하는 최종 curl DELETE 메서드가 있습니다.

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

이 삭제 컬 코드를 보유하고 ajax에서 값을 전달하는 php (method : delete)에 대한 ajax 호출을 수행하는 방법을 알려주시겠습니까?
— user1788736

@ user1788736 저는 Ajax를 잘 못하지만이 방법을 실행하는 PHP 파일을 만들 수 있고 Ajax를 사용하여 POST를 사용하여 해당 PHP 파일로 데이터를 보낼 수 있습니다. 위의 방법이 혼란 스럽다고 생각되면 다시 살펴보십시오. $ url은 대화해야하는 서버 ( someserver.com )이고 $ path는 URL (/ something /) 뒤의 항목입니다. 내가 이것을 분리 한 유일한 이유는 항상 동일한 서버로 보내야하지만 동적 경로를 사용하기 때문입니다. 이해가 되길 바랍니다.
— Bolli

헤더가 필요하지 않습니까?
— er.irfankhan11

동일한 코드를 사용하고 있으며 Paypal이 http 코드를 반환합니다. 그러나 나는 항상 400을 받았습니다.
— er.irfankhan11

1
내 수업에서 개인 변수 인 @kuttoozz. 요청을해야하는 URL입니다. api.someurl.com 과 같은 것일 수 있으며 $ path는 해당 url (/ something /) 뒤에 옵니다 . 해당 값을 URL로 변경하거나 제거하고 $ path 변수에 전체 URL을 포함 할 수 있습니다. 말이 돼?
— Bolli

19

GET, POST, DELETE, PUT 모든 종류의 요청을 호출하려면 하나의 공통 함수를 만들었습니다.

function CallAPI($method, $api, $data) {
    $url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL 삭제 방법

$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);

CALL 게시 방법

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);

CALL Get 메서드

$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);

CALL Put 방법

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);

잘 했어. 그냥 참고 : 삭제에 대한 HTTP 응답 코드 (204)입니다 당신이 :) 좋은 반응 모든 20 개 배 코드를 고려해야한다고 생각합니다
— ryuujin

0

wsse 인증으로 내 자신의 클래스 요청

class Request {

    protected $_url;
    protected $_username;
    protected $_apiKey;

    public function __construct($url, $username, $apiUserKey) {
        $this->_url = $url;     
        $this->_username = $username;
        $this->_apiKey = $apiUserKey;
    }

    public function getHeader() {
        $nonce = uniqid();
        $created = date('c');
        $digest = base64_encode(sha1(base64_decode($nonce) . $created . $this->_apiKey, true));

        $wsseHeader = "Authorization: WSSE profile=\"UsernameToken\"\n";
        $wsseHeader .= sprintf(
            'X-WSSE: UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->_username, $digest, $nonce, $created
        );

        return $wsseHeader;
    }

    public function curl_req($path, $verb=NULL, $data=array()) {                    

        $wsseHeader[] = "Accept: application/vnd.api+json";
        $wsseHeader[] = $this->getHeader();

        $options = array(
            CURLOPT_URL => $this->_url . $path,
            CURLOPT_HTTPHEADER => $wsseHeader,
            CURLOPT_RETURNTRANSFER => true, 
            CURLOPT_HEADER => false             
        );                  

        if( !empty($data) ) {
            $options += array(
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_SAFE_UPLOAD => true
            );                          
        }

        if( isset($verb) ) {
            $options += array(CURLOPT_CUSTOMREQUEST => $verb);                          
        }

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);                   

        if(false === $result ) {
            echo curl_error($ch);
        }
        curl_close($ch);

        return $result; 
    }
}

array_merge의 사용 + = instaead
— Adriwan Kenoby

그것은 아마도 효과가 있지만 문제에 대한 불필요하게 복잡한 해결책입니다.
— Samuel Lindblom

0

switch ($ method) {case "GET": curl_setopt ($ curl, CURLOPT_CUSTOMREQUEST, "GET"); 단절; case "POST": curl_setopt ($ curl, CURLOPT_CUSTOMREQUEST, "POST"); 단절; case "PUT": curl_setopt ($ curl, CURLOPT_CUSTOMREQUEST, "PUT"); 단절; case "DELETE": curl_setopt ($ curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 단절; }


-19
    $json empty

public function deleteUser($extid)
{
    $path = "/rest/user/".$extid."/;token=".$this->__token;
    $result = $this->curl_req($path,"**$json**","DELETE");
    return $result;

}

감사. 이 특정 REST 호출에서 JSON 부분은 비어 있어야하므로 문제가되지 않습니다. 하지만 어쨌든 감사합니다
— Bolli

여기서 무슨 $json empty뜻입니까? 어쨌든이 함수 내부의 범위에 있지 않으므로의 사용은 $json아무것도하지 않습니다.
— halfer

이 답변을 삭제 해달라고 요청했지만 중재자가 아니요라고 답했습니다. 이 답변의 포스터는 2014 년 이후로 로그인하지 않았습니다.
— halfer
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.