简体   繁体   中英

How to get response-header from curl post request?

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
curl_setopt($ch, CURLOPT_USERPWD, 'PortalPartner' . ":" . 'W169F1320&8d');

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header = curl_getinfo($ch);
curl_close($ch);

I need to see the response header where is will be token for my next request, but I can not. When I use this request in insomnia or postman I can see response header but I can not in code.

You can specify a callback function for headers using curl_setopt with CURLOPT_HEADERFUNCTION . The callback will be execute for each header line.

$headers=[];
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use ($headers){
    array_push($headers, $header);
});

Note that this will be executed for every header line including the initial HTTP/ line and will be provided with a simple string. You will need to split each line on ":" to separate the key and value. Typically, I would parse the headers into an associative array.

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