How to get info on sent PHP curl request

前端 未结 4 1940
故里飘歌
故里飘歌 2020-12-05 04:22

I\'m trying to debug a curl request to a webservice \'getToken\' endpoint.

I\'m not 100% confident that the URL and the auth info is getting written in to the curl

4条回答
  •  星月不相逢
    2020-12-05 04:35

    If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    
    curl_exec($ch);
    
    $info = curl_getinfo($ch);
    print_r($info['request_header']);
    

    This will print:

    GET /bar HTTP/1.1
    Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
    Host: foo.com
    Accept: */*
    

    Note the auth details are base64-encoded:

    echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
    // prints: someusername:secretpassword
    

    Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

    curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));
    

提交回复
热议问题