Search code examples
phpapirestcurlapache-cloudstack

PHP CURL fetch header from URL and set it to variable


I have a piece of code that trying to call Cloudstack REST API :

function file_get_header($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);

        $datas = curl_exec($ch);
        curl_close($ch);
        return $datas;
} 

        $url = "http://10.151.32.51:8080/client/api?" . $command . "&" . $signature . "&" . $response;

        echo $test = file_get_header($url);

And the output is like this :

HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT

What I am trying to do is how to print JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 only and assign it into variable? Thankss,


Solution

  • Simple, just match the part of the string you want with preg_match:

    <?php
    
        $text = "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client    Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT";
    
        preg_match("/JSESSIONID=\\w{32}/u", $text, $match);
    
        echo $result = implode($match);
    
    ?>