Curl, follow location but only get header of the new location?

前端 未结 7 1599
情书的邮戳
情书的邮戳 2020-12-19 13:56

I know that when I set CURLOPT_FOLLOWLOCATION to true, cURL will follow the Location header and redirect to new page. But is it possible only to get header of the new page w

相关标签:
7条回答
  • 2020-12-19 14:45

    No. You'd have to disable FOLLOWLOCATION, extract the redirect URL from the response, and then issue a new HEAD request with that URL.

    0 讨论(0)
  • 2020-12-19 14:45

    Appears to be a duplicate of PHP cURL: Get target of redirect, without following it

    However, this can be done in 3 easy steps:

    Step 1. Initialise curl

    curl_init($ch); //initialise the curl handle
    //COOKIESESSION is optional, use if you want to keep cookies in memory
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    

    Step 2. Get the headers for $url

    curl_setopt($ch, CURLOPT_URL, $url); //specify your URL
    curl_setopt($ch, CURLOPT_HEADER, true); //include headers in http data
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); //don't follow redirects
    $http_data = curl_exec($ch); //hit the $url
    $curl_info = curl_getinfo($ch);
    $headers = substr($http_data, 0, $curl_info["header_size"]); //split out header
    

    Step 3. Parse the headers to get the new URL

    preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!", $headers, $matches);
    $url = $matches[1];
    

    Once you have the new URL you can then repeat steps 2-3 as often as you like.

    0 讨论(0)
  • 2020-12-19 14:53

    And for analyze headers, your can use CURLOPT_HEADERFUNCTION

    0 讨论(0)
  • 2020-12-19 14:56

    Set CURLOPT_FOLLOWLOCATION as false and CURLOPT_HEADER as true, and get the "Location" from the response header.

    0 讨论(0)
  • 2020-12-19 14:57

    Make sure you set CURLOPT_HEADER to True to get the headers in the response, otherwise the response returned as blank string

    0 讨论(0)
  • 2020-12-19 14:58

    You can get the redirect URL directly with curl_getinfo:

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_COOKIESESSION, false);
      curl_setopt($ch, CURLOPT_URL, $url); //specify your URL
      curl_setopt($ch, CURLOPT_HEADER, true); //include headers in http data
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); //don't follow redirects
      $http_data = curl_exec($ch); //hit the $url
      $redirect = curl_getinfo($ch)['redirect_url'];
      curl_close($ch);
    
      return $redirect;
    
    0 讨论(0)
提交回复
热议问题