12

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 right 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);
    
    ?>

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

Comments

13

'Hash:$hash' should be either "Hash: $hash" (double quotes) or 'Hash: '.$hash

The same goes for your URL passed in CURLOPT_URL

1 Comment

Yay! To think it's variable interpolation that has been bugging me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.