Search code examples
phpcurlphp-7

Get the value of CURLOPT_HTTPHEADER from cURL


I have the method below that is to get the response from webserver using cURL.

function login (string $_login, string $_password) : string {

    $url = "https://acweb.net.br/api/orcamentos/login";  

    $fields = [
        "login"    => $_login,
        "password" => $_password
    ];

    $headers = [
        "Try" => "Trying"
    ];

    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_URL, $url);
    curl_setopt( $ch, CURLOPT_POST, true);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    return curl_exec( $ch );

}

It works fine!

i can get the value of $_POST with

print_r ($_POST)

But i can't get the value of CURLOPT_HTTPHEADER.

EDIT:

I did try so:

print_r ($_SERVER)

but it wasn't there.

How can i get the value of CURLOPT_HTTPHEADER?

all HTTP_headers in $_SERVER:

[HTTP_HOST] => ctemcasb.com.br
[HTTP_CONNECTION] => keep-alive
[HTTP_UPGRADE_INSECURE_REQUESTS] => 1
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
[HTTP_SEC_FETCH_USER] => ?1
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
[HTTP_SEC_FETCH_SITE] => none
[HTTP_SEC_FETCH_MODE] => navigate
[HTTP_ACCEPT_ENCODING] => gzip, deflate, br
[HTTP_ACCEPT_LANGUAGE] => pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7
[HTTP_COOKIE] => PHPSESSID=j4cqqdc83fia68nk0gsglqk1bv

HTTP_TRY, not exists.

And now?

I did this in the server:

print_r($_SERVER)

and

print_r ($_SERVER["HTTP_TRY]);

Solution

  • The headers shouldn't be an associative array, it should be an indexed array of strings.

    $headers = [
        'Try: Trying',
        'Content-Type: text/html',
        ...
    ]; 
    

    Then you should be able to access the header with: $_SERVER['HTTP_TRY'] since custom headers are prefixed with HTTP_