How can I find where I will be redirected using cURL?

前端 未结 7 1853
小鲜肉
小鲜肉 2020-11-22 03:53

I\'m trying to make curl follow a redirect but I can\'t quite get it to work right. I have a string that I want to send as a GET param to a server and get the resulting URL.

7条回答
  •  青春惊慌失措
    2020-11-22 04:36

    The chosen answer here is decent but its case sensitive, doesn't protect against relative location: headers (which some sites do) or pages that might actually have the phrase Location: in their content... (which zillow currently does).

    A bit sloppy, but a couple quick edits to make this a bit smarter are:

    function getOriginalURL($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
    
        // if it's not a redirection (3XX), move along
        if ($httpStatus < 300 || $httpStatus >= 400)
            return $url;
    
        // look for a location: header to find the target URL
        if(preg_match('/location: (.*)/i', $result, $r)) {
            $location = trim($r[1]);
    
            // if the location is a relative URL, attempt to make it absolute
            if (preg_match('/^\/(.*)/', $location)) {
                $urlParts = parse_url($url);
                if ($urlParts['scheme'])
                    $baseURL = $urlParts['scheme'].'://';
    
                if ($urlParts['host'])
                    $baseURL .= $urlParts['host'];
    
                if ($urlParts['port'])
                    $baseURL .= ':'.$urlParts['port'];
    
                return $baseURL.$location;
            }
    
            return $location;
        }
        return $url;
    }
    

    Note that this still only goes 1 redirection deep. To go deeper, you actually need to get the content and follow the redirects.

提交回复
热议问题