Бывает так что сервер перенаправляет на другой URL. Например Google, если перейти на https://google.com
c IP из РФ он делает 302-й редирект на https://www.google.ru
.
Чтобы CURL сам переходил на новый URL, нужно добавить параметр:
Но если он не помогает, то можно применить функцию:
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops >= $curl_max_loops) {
$curl_loops = 0;
return false;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$dd = explode("\r\n\r\n", $data); // или $dd = explode("\r\n", $data);
$header = $dd[0];
$data = @$dd[1];
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
if (!$url) {
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (empty($url['scheme'])) {
$url['scheme'] = $last_url['scheme'];
}
if (empty($url['host'])) {
$url['host'] = $last_url['host'];
}
if (empty($url['path'])) {
$url['path'] = $last_url['path'];
}
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query'] ? '?' . $url['query'] : '');
curl_setopt($ch, CURLOPT_URL, $new_url);
return curl_redir_exec($ch);
} else {
$curl_loops = 0;
return $data;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$html = curl_redir_exec($ch);
curl_close($ch);
echo $html;