简体   繁体   中英

How to pass a http header using a variable in curl using PHP

My code to add header is:

$apikey="xyz";
     curl_setopt($handle, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: application/json',
                                            'Accept: application/json',
                                            'X-Auth-Token: $apikey'                                 
                                            ));

But I am getting an error showing that **This request requires HTTP Authentication.**Now I want to know whether I am right? If Yes why I am getting error.If I am wrong how can do this..

Thankyou,

Use double quotes if you want your variable to be interpolated by PHP, ie "X-Auth-Token: $apikey" .

For more info see PHP: Strings .

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http:www.example.com');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('name' => 'Bhuvanagiri Gireesh') );
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Accept: application/json';
    $headers[] = 'key: license-key ';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

There are many ways to achieve it but, this is the easiest way to add headers in curl

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