我正在开发一个应用程序来使用Youtube Data API。我认为 CURL 永远是比使用 PHP file_get_contents()
更好的选择。使用 CURL,我需要知道哪些所有标头都应包含在优化性能的请求中。
我需要设置一些超时设置,错误处理方法等;
提前感谢。
您可以使用 http 包装器进行 file_get_contents (http://us1.php.net/manual/en/function.stream-context-create.php):
$options = array(
'http'=>array(
'method'=>"GET",
'timeout' => 60
)
);
$context = stream_context_create($options);
file_get_contents("http://google.com", false, $context);
print_r($http_response_header);
你可以尝试这样的事情:
$ch = curl_init('your url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3',
'Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7',
'Connection: keep-alive',
'Pragma: no-cache',
'Cache-Control: no-cache'
));
$result = curl_exec($ch);
if($result == FALSE) {
var_dump(curl_error($ch)); //handling error
} else { //success
echo $result;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_URL, $IP);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('User-Agent: 1.11.4 Red Hat modified',"Host : $host",'Connection: Keep-Alive'));//it might need
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);//just get the header info only
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);//set your time out
$data = curl_exec($ch);
return $data;