【问题标题】:PHP CURL fetch header from URL and set it to variablePHP CURL 从 URL 获取标头并将其设置为变量
【发布时间】:2014-07-21 22:54:52
【问题描述】:

我有一段代码试图调用 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);

输出是这样的:

HTTP/1.1 200 OK 服务器: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

我要做的是如何仅打印 JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 并将其分配给变量?谢谢,

【问题讨论】:

    标签: php api rest curl apache-cloudstack


    【解决方案1】:

    这是一种将所有标头解析为一个不错的关联数组的方法,因此您可以通过请求 $dictionary['header-name'] 来获取任何标头值

    $url = 'http://www.google.com';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $datas = curl_exec($ch);
    
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($datas, 0, $header_size);
    curl_close($ch);
    
    echo ($header);
    $arr = explode("\r\n", $header);
    $dictionary = array();
    foreach ($arr as $a) {
        echo "$a\n\n";
        $key_value = explode(":", $a, 2);
        if (count($key_value) == 2) {
            list($key, $value) = $key_value;
            $dictionary[$key] = $value;
        }
    }
    
    //uncomment the following line to see $dictionary is an associative-array of Header keys to Header values
    //var_dump($dictionary);
    

    【讨论】:

      【解决方案2】:

      简单,只要将你想要的字符串部分与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);
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 2016-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多