How to get/set Header in Rest Server API?

Abdul Manan picture Abdul Manan · Jun 13, 2015 · Viewed 16.7k times · Source

i have a chriskacerguis Rest Server ,that listen for a client request as usually an API Server do. base on client request i want to send/response some data to client in header only.

my questions are:

  1. how do i access Client header first?

    then

  2. how do i set Header in Rest Server?

This is how i send a request to REST SERVER:

function request_curl($url = NULL) {
        $utc = time();
        $post = "id=1&CustomerId=1&amount=2450&operatorName=Jondoe&operator=12";
        $header_data = array(
            "Content-Type: application/json",
            "Accept: application/json",
            "X-API-KEY:3ecbcb4e62a00d2bc58080218a4376f24a8079e1",
            "X-UTC:" . $utc,
        );
        $ch = curl_init();
        $curlOpts = array(
            CURLOPT_URL => 'http://domain.com/customapi/api/clientRequest',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $header_data,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $post,
            CURLOPT_HEADER => 1,
        );
        curl_setopt_array($ch, $curlOpts);
        $answer = curl_exec($ch);
        // If there was an error, show it
        if (curl_error($ch)) {
            die(curl_error($ch));
        }

        curl_close($ch);
        echo '<pre>';
        print_r($answer);
        echo '</pre>';
    }

Below is my REST SERVER function that listen request and will response a header:

public function clientRequest_post() {
        // Getting Post Data
        $entityBody = file_get_contents('php://input', 'r');
       $this->response($entityBody,200);
      //getting header data ,no idea 
    }

Answer

Syed Sajid picture Syed Sajid · Jun 13, 2015

May be try php function getallheaders() which will fetch all the header data for you. If you want to convert it into array, use foreach.

So this will get you the header data and will convert it into array

$headers=array();
foreach (getallheaders() as $name => $value) {
    $headers[$name] = $value;
}

Now if you want to get body and convert it into array as well

$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);

The final function will look something like this...

public function clientRequest_post() {

    $headers=array();
    foreach (getallheaders() as $name => $value) {
        $headers[$name] = $value;
    }

    $entityBody = file_get_contents('php://input', 'r');
    parse_str($entityBody , $post_data);


    $this->response($entityBody, 200);


}

Btw, I assume $this->response($entityBody,200); will generate the response for you. Best of luck with it