超絶自分用。
<?php
class Socket {
private $connect;
private $ua;
private $url;
private $redirectCount;
public function __construct()
{
$this->connect = curl_init();
}
public function get($autoReboot = true)
{
$this->setOptions();
$contents = curl_exec($this->connect);
$this->redirectCount = curl_getinfo($this->connect, CURLINFO_REDIRECT_COUNT);
curl_close($this->connect);
if ($autoReboot) {
$this->reboot();
}
return $contents;
}
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* default user agent
* @return Socket
*/
public function setPcUa()
{
$this->ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36';
return $this;
}
/**
* custom user agent
* @param string $isAndroid
* @return Socket
*/
public function setSpUa($isAndroid = false)
{
if ($isAndroid) {
$this->ua = 'Mozilla/5.0 (Linux; U; Android 4.1.1; ja-jp; Galaxy Nexus Build/JRO03H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30';
} else {
$this->ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A405 Safari/600.1.4';
}
return $this;
}
public function reboot()
{
$this->connect = curl_init();
$this->setPcUa();
$this->resetUrl();
return $this;
}
public function getLastRedirectCount()
{
return $this->redirectCount;
}
private function resetUrl()
{
$this->url = null;
}
private function setOptions()
{
$this->validation();
curl_setopt($this->connect, CURLOPT_URL, $this->url);
curl_setopt($this->connect, CURLOPT_USERAGENT, $this->ua);
curl_setopt($this->connect, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($this->connect, CURLOPT_TIMEOUT, 10);
curl_setopt($this->connect, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->connect, CURLOPT_FAILONERROR, true);
curl_setopt($this->connect, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->connect, CURLOPT_AUTOREFERER, true);
}
private function validation()
{
try {
if (empty($this->url)) {
throw new RuntimeException();
}
} catch (Exception $e) {
die('Please set the url.');
}
}
}
使い方は下記の通り。
$socket = new Socket(); $url = 'http://www.yahoo.co.jp'; $result = $socket->setUrl($url)->get(); // リダイレクトカウントも取れるよ $socket->getLastRedirectCount()
まぁメリットはcurlを使っているのでfile_get_contents()よりも速いよってくらいかな。