Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Custom Header with CURL

I want to send a request to a web service via an API as shown below, i have to pass a custom http header(Hash), i'm using CURL, my code seems to work but I'm not getting the rigth response, I'm told it has to do with the hash value, though the value has been seen to be correct, is there anything wrong with the way I'm passing it or with the code itself.

 <?php
    $ttime=time();
    $hash="123"."$ttime"."dfryhmn";
    $hash=hash("sha512","$hash");
    $curl = curl_init();
    curl_setopt($curl,CURLOPT_HTTPHEADER,array('Hash:$hash'));      
    curl_setopt ($curl, CURLOPT_URL, 'http://web-service-api.com/getresult.xml?clientid=456&time=$ttime');  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
    $xml = curl_exec ($curl);  

    if ($xml === false) {
        die('Error fetching data: ' . curl_error($curl));  
    }
    curl_close ($xml);  

    echo htmlspecialchars("$xml", ENT_QUOTES);

    ?>
like image 911
bodesam Avatar asked Dec 07 '12 21:12

bodesam


1 Answers

If you need to get and set custom http headers in php, the following short tutorial is really useful:

Sending The Request Header

$uri = 'http://localhost/http.php';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
    CURLOPT_HTTPHEADER  => array('X-User: admin', 'X-Authorization: 123456'),
    CURLOPT_RETURNTRANSFER  =>true,
    CURLOPT_VERBOSE     => 1
));
$out = curl_exec($ch);
curl_close($ch);
// echo response output
echo $out;

Reading the custom header

print_r(apache_request_headers());

you should see

Array
(
    [Host] => localhost
    [Accept] => */*
    [X-User] => admin
    [X-Authorization] => 123456
    [Content-Length] => 9
    [Content-Type] => application/x-www-form-urlencoded
)

Custom Headers with PHP CGI

in .htaccess

RewriteEngine On
RewriteRule .? - [E=User:%{HTTP:X-User}, E=Authorization:%{HTTP:X-Authorization}]

Reading the custom headers from $_SERVER

echo $_SERVER['User'];    
echo $_SERVER['Authorization'];

Resources

  • http://www.omaroid.com/php-get-and-set-custom-http-headers/
  • How can I get PHP to display the headers it received from a browser?
like image 161
RafaSashi Avatar answered Sep 28 '22 13:09

RafaSashi