简体   繁体   中英

Headers not being set using curl_setopt PHP

I'm using curl_setopt to set the header in my request. Specifically, I want to make it so the header includes what kind of authorization is being used.

  // Define headers to use
  $header = array(
         'HTTP/1.1',
         'Content-type: text/plain',
         'Authorization: Basic ' . base64_encode("$username:$password")
  );

// Below I prepare the request

$ch = curl_init();

 curl_setopt($ch, CURLOPT_URL,$URL);
 curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);;
 curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // set custom header
 curl_setopt($ch, CURLOPT_HEADER, true);
 curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

 $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code

 if (curl_errno($ch)) {
     echo 'CURL Error: ' . curl_error($ch);
 }

 $result=curl_exec ($ch);

 echo $result;

 curl_close ($ch);

My use case is running tcpdump to analyze the header (by finding the string "Authorization: Basic" and thus getting the base64 encoding of username:password

Thus when this php program sends out this request to $URL (by loading this program's page), TCP Dump should detect the base64 encoding that uis being sent out, right?

However, tcpdump doesn't pickup the header and I think it's because I'm not setting the headers correctly.

You need to execute the curl request.

$result = curl_exec($ch);

//remember to close the connection too
curl_close($ch).

If you do not call curl_exec() , you are never sending the request, and therefore never sending the headers.

Looks OK to me. However, you don't need the Authorization header when using CURLOPT_USERPWD since it will override any existing Authorizations headers. in the headers array.

A suggestion is to debug you curl request by sending it to http://requestb.in .

The way you set HTTP headers is right.
Did you forget to call curl_exec($ch); after all that?

you have to run curl_exec first:

$result=curl_exec ($ch);

and then check the status code:

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code

if (curl_errno($ch)) {
    echo 'CURL Error: ' . curl_error($ch);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM