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

前端 未结 7 1933
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    2020-11-22 04:22

    The answer above didn't work for me on one of my servers, something to to with basedir, so I re-hashed it a little. The code below works on all my servers.

    $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);
    $a = curl_exec($ch);
    curl_close( $ch ); 
    // the returned headers
    $headers = explode("\n",$a);
    // if there is no redirection this will be the final url
    $redir = $url;
    // loop through the headers and check for a Location: str
    $j = count($headers);
    for($i = 0; $i < $j; $i++){
    // if we find the Location header strip it and fill the redir var       
    if(strpos($headers[$i],"Location:") !== false){
            $redir = trim(str_replace("Location:","",$headers[$i]));
            break;
        }
    }
    // do whatever you want with the result
    echo redir;
    

提交回复
热议问题