cURL,获取重定向url到变量

Vam*_*a B 26 php redirect curl

我正在使用curl填写表格.完成帖子后,处理表单的其他脚本将重定向到另一个URL.我想将此重定向URL转换为变量.

EGL*_*101 43

找到重定向网址的简便方法(如果您不想提前知道)

$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
Run Code Online (Sandbox Code Playgroud)

  • 它是'CURLINFO_REDIRECT_URL` (4认同)

Rob*_*itt 34

你会用的

curl_setopt($CURL, CURLOPT_HEADER, TRUE);
Run Code Online (Sandbox Code Playgroud)

并解析标题的location标题


nic*_*ika 8

在这里,我获得资源http头,然后我将头解析为数组$ retVal.我从这里获得了解析头文件的代码(http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/)你也可以使用http://php.net/ manual/en/function.http-parse-headers.php如果你有(PECL pecl_http> = 0.10.0)

        $ch = curl_init();
        $timeout = 0;
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        // Getting binary data
        $header = curl_exec($ch);
        $retVal = array();
        $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
        foreach( $fields as $field ) {
            if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
                $match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
                if( isset($retVal[$match[1]]) ) {
                    $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
                } else {
                    $retVal[$match[1]] = trim($match[2]);
                }
            }
        }
//here is the header info parsed out
echo '<pre>';
print_r($retVal);
echo '</pre>';
//here is the redirect
if (isset($retVal['Location'])){
     echo $retVal['Location'];
} else {
     //keep in mind that if it is a direct link to the image the location header will be missing
     echo $_GET[$urlKey];
}
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)