cURLの様々な使い方

cURLの様々な使い方

基本

$ch = curl_init();
 
curl_setopt( $ch, CURLOPT_URL, $url );
 
// option...
 
$result = curl_exec( $ch );
 
curl_close( $ch );

POST

$params = [ 'key'=>'value', ];
 
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params) );

Cookieの利用

$cookie = '/cookie.text';
 
curl_setopt( $ch, CURLOPT_COOKIEFILE, $cookie );
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );

タイムアウト設定

curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );

エラーハンドリング

curl_setopt( $ch, CURLOPT_FAILONERROR, true );

リダイレクト

curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); // リダイレクトの許可
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 ); // maxリダイレクト数
curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); // リファラーの自動追加

リダイレクト先URL取得

$ch = curl_init();
 
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
 
// option...
 
curl_exec( $ch );
$result = curl_getinfo( $ch, CURLINFO_EFFECTIVE_URL );
 
curl_close( $ch );

SSL対策

curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );

BASIC認証

$id = 'user';
$pass = 'pass1234';
 
curl_setopt( $ch, CURLOPT_USERPWD, $id .":". $pass);

UAの設定

curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");

リクエストヘッダーの設定

$headers = array(
    "HTTP/1.0",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Encoding:gzip ,deflate",
    "Accept-Language:ja,en-us;q=0.7,en;q=0.3",
    "Connection:keep-alive",
    "User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:26.0) Gecko/20100101 Firefox/26.0"
  );
 
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );

文字化け対策

curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
 
$result = curl_exec( $ch );
$result = mb_convert_encoding(result, 'UTF-8', 'ASCII, JIS, UTF-8, SJIS');