【发布时间】:2011-05-03 01:06:25
【问题描述】:
我正在使用 curl 来填写表格。发布完成后,处理表单的另一个脚本将重定向到另一个 URL。我想将此重定向 URL 放入变量中。
【问题讨论】:
我正在使用 curl 来填写表格。发布完成后,处理表单的另一个脚本将重定向到另一个 URL。我想将此重定向 URL 放入变量中。
【问题讨论】:
找到重定向网址的简单方法(如果您不想提前知道)
$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
【讨论】:
CURLINFO_REDIRECT_URL
CURLINFO_EFFECTIVE_URL 为我工作。 CURLINFO_REDIRECT_URL 没有返回任何东西,也许我只是做错了什么=/
你会使用
curl_setopt($CURL, CURLOPT_HEADER, TRUE);
并解析 location 标头的标头
【讨论】:
在这里,我获取资源 http 标头,然后将标头解析为数组 $retVal。我从这里获得了解析标头的代码 (http://www.bhootnath.in/blog/2010/10/parse-http-headers-in-php/) 如果你有 (PECL pecl_http >= 0.10.0)
,你也可以使用 http://php.net/manual/en/function.http-parse-headers.php $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);
【讨论】:
preg_replace /e modifier is deprecated 有人可以更新这个答案吗?
您可能希望将 CURLOPT_FOLLOWLOCATION 设置为 true。
或者将 CURLOPT_HEADER 设置为 true,然后使用正则表达式获取 Location 标头。
【讨论】: