private $_config = array(
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => false,
...
}
private $follow_location = false;
private function canFollow() {
return (!ini_get('open_basedir') and !ini_get('safe_mode'));
}
public function follow($follow) {
$this->follow_location = $follow;
return $this;
}
private function _exec($url){
$this->setOption(CURLOPT_URL, $url);
# redirects
if($this->follow_location) {
if($this->canFollow()) {
$this->setOption(CURLOPT_FOLLOWLOCATION, true);
}
else {
$this->setOption(CURLOPT_FOLLOWLOCATION, false);
}
}
$response = curl_exec($this->_ch);
$header_size = curl_getinfo($this->_ch, CURLINFO_HEADER_SIZE);
$header = mb_substr($response, 0, $header_size);
$content = mb_substr($response, $header_size);
# redirects
if($this->follow_location) {
$http_code = curl_getinfo($this->_ch, CURLINFO_HTTP_CODE);
if(in_array($http_code, array(301, 302, 303))) {
if(preg_match('/Location: (.+?)\n/', $header, $matches)) {
$url = trim($matches[1]);
return $this->_exec($url);
}
}
}
if(!curl_errno($this->_ch))
return $content;
else
throw new CException(curl_error($this->_ch));
}
public function getRealUrl($url) {
$this->follow(true);
$this->setOption(CURLOPT_URL, $url);
$this->setOption(CURLOPT_NOBODY, true);
$this->setOption(CURLOPT_FOLLOWLOCATION, false);
$header = curl_exec($this->_ch);
if(preg_match('/Location: (.+?)\n/', $header, $matches)) {
$url = trim($matches[1]);
return $this->getRealUrl($url);
}
return $url;
}