Home » Php » json – XAMPP PHP curl – CURLOPTHTTPHEADER not working

json – XAMPP PHP curl – CURLOPTHTTPHEADER not working

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am working with XAMPP. Usually I have no issues receiving JSON with PHP. Today I am working with an API that calls for headers in the call. I get no response, despite spending hours going over my code multiple times.

I see other threads discuss how XAMPP apache may overwrite my headers, or how the API’s server wont reply to anything not a browser.

If APache is overwriting the headers I send out, how do I address that??

When using curl_error and apache_request_headers, I see no error, and the user agent seems just fine. Making this API call works just fine from Postman.

Also, why exactly is my API_headers array not visible from my fetch_json function, but my other variable, $API_base is??

I really spent hours searching online before thinking of posting this question.

Thank you in advance.

API in question is….
https://www.oilpriceapi.com/

    <?php 

require('mysqli_connect.php'); // Connect to the db.

/*

    API source
    https://www.oilpriceapi.com/

    API call for filling our Oil Brent table and Oil WTI
    These are two, among many, classifications of Oil that we will mine data from
    -WTI, which is sourced from Oklahoma
    0Brent, which is sourced from near the United Kingdom


    After filling our tables, we can use another program to support daily updates.
    These daily programs can be automated with Linux or Windows Task Scheduler.


    Base API call, that will modified with string replace.
    Our API source has different amounts of daily data for Brent and WTI
    Thuse, page number (at the end) has to be altered.


    Oil API token used in HTTP Request Header
    token == Token 8b3df4ab0b54394df588f3015daa7f77

*/

$API_base = 'http://api.oilpriceapi.com/v1/prices?by_code=xoil_codex&by_type=daily_average_price&page=xnumx';



//This API requires use of headers in the request
//We keep it in this array, to call upon below
$API_headers = 
     array(

            'Host: localhost',
            'Connection: keep-alive',
            'Cache-Control: max-age=0',
            'Upgrade-Insecure-Requests: 1',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
            'Sec-Fetch-User: ?1',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Sec-Fetch-Site: none',
            'Sec-Fetch-Mode: navigate',
            'Referer: http://localhost/capstone2020/',
            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: en-US,en;q=0.9',


           //This is what the API explcitily calls for 
            'Content-Type: application/json',
            'Authorization: Token 8b3df4ab0b54394df588f3015daa7f77'       


          );

//Array of our Oil Classifications, to be used with string replace
$oil_code = ['BRENT_CRUDE_USD','WTI_USD'];


//=========================================================================================================

?>


<?php

/* 
    In this function, here now, we make our HTTP call.
    it calls upon our altered API URL, and our headers above.
    It returns the JSON to the function caller below.

*/

    function fetch_json($API_base)
    {

        $API_headers = 
           array(



            'Host: localhost',
            'Connection: keep-alive',
            'Cache-Control: max-age=0',
            'Upgrade-Insecure-Requests: 1',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
            'Sec-Fetch-User: ?1',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Sec-Fetch-Site: none',
            'Sec-Fetch-Mode: navigate',
            'Referer: http://localhost/capstone2020/',
            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: en-US,en;q=0.9',

            'Content-Type: application/json',
            'Authorization: Token 8b3df4ab0b54394df588f3015daa7f77'       


                );

        $curl = curl_init();

        curl_setopt_array($curl, 
        [
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HTTPHEADER => $API_headers ,
            CURLOPT_URL => $API_base
        ]);


        $response = curl_exec($curl);

        curl_close($curl);

        return json_decode($response, true);

    }


/*
    here, we pass our base API URL to swap oil classification call
    As it is the innner function, below, it is the one called first

*/

    function build_url($API_base,$oil_code,$page_num)
    {
        $replace_oil_code = str_replace("xoil_codex",$oil_code,$API_base);
        $replace_page_num =  str_replace("xnumx",$page_num,$replace_oil_code);

        $new_URL = $replace_page_num;

        echo $new_URL;

        return $new_URL;
    }


//==========================================================================================================
?>


<?php

    //going through the oil classification-code array
    for($a = 0 ;  $a < count($oil_code) ; $a++ )
    {

        /*  
            going through the page numbers, as each page holds 100 results
            brent has many, many pages. WTI has few pages.
            Thus, different page ranges in use for our API calls.

        */

        $pageNum = [85, 2];

        for($page = 1; $page <=  $pageNum[$a] ; $page++)
        {
                $response1 = fetch_json(build_url($API_base , $oil_code[$a] , $page));


                echo $response1;

                if($response1 <> 'expired_token')
                 {
                    foreach($response1['data']['prices'] as $day => $response)
                    {

                            $price = $response['price'];
                            $price = mysqli_real_escape_string($dbc,trim($price)); 

                            $formatted = $response['formatted'];
                            $formatted = mysqli_real_escape_string($dbc,trim($formatted));

                            $currency = $response['currency'];
                            $currency = mysqli_real_escape_string($dbc,trim($currency));            

                            $code = $response['code'];
                            $code = mysqli_real_escape_string($dbc,trim($code));    

                            $created_at = $response['created_at'];
                            $created_at = mysqli_real_escape_string($dbc,trim($created_at));    

                            $type = $response['type'];
                            $type = mysqli_real_escape_string($dbc,trim($type));    


                            $table =  mysqli_real_escape_string($dbc,trim($oil_code[$a]));


                            $insert_this = "INSERT IGNORE INTO $table (price, formatted, currency, code, created_at, type) 
                                            VALUES 
                                            (DATE('$price'), '$formatted', '$currency', '$code', '$created_at', '$type')";


                            $result = mysqli_query($dbc,$insert_this);

                    }
                }



            else 
            {
                //If token is all used up, display that message to screen.
                echo $response;
                break;
            }
        }

    }

?>

Thanks in advance everyone!!!

How to&Answers: