目次

09 curl

$conn = curl_init();
curl_setopt($conn, CURLOPT_URL, $url);
curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($conn, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($conn, CURLOPT_TIMEOUT, 5);
curl_setopt($conn, CURLOPT_HEADER, FALSE);
$ret = curl_exec($conn);
curl_close($conn);

$result = json_decode($ret, true);
return $result;

Basic認証の場合

curl_setopt($conn, CURLOPT_USERPWD, "User:Password");

cookieを利用する場合

$cookie=tempnam(sys_get_temp_dir(),'cookie_');
$conn = curl_init();
curl_setopt($conn, CURLOPT_COOKIEJAR,$cookie);
curl_setopt($conn, CURLOPT_URL, $url);
curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($conn, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($conn, CURLOPT_TIMEOUT, 5);
curl_setopt($conn, CURLOPT_HEADER, FALSE);
$ret = curl_exec($conn);
curl_close($conn);
unlink($cookie);

$result = json_decode($ret, true);
return $result;
POST
$PASSWORD = 'hogehoge';
$USERNAME = 'hoge';

$POST_DATA = array(
    'foo' => 'bar'
);

$conn = curl_init();
curl_setopt($conn, CURLOPT_URL, $url);
curl_setopt($conn, CURLOPT_POST, TRUE);
curl_setopt($conn, CURLOPT_POSTFIELDS, http_build_query($POST_DATA));
curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($conn, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($conn, CURLOPT_TIMEOUT, 5);
curl_setopt($conn, CURLOPT_HEADER, FALSE);
curl_setopt($conn, CURLOPT_USERPWD, $USERNAME . ":" . $PASSWORD);
$ret = curl_exec($conn);
curl_close($conn);

エラーの確認

curl_error($conn);

curl Timeout

CURLOPT_TIMEOUT/CURLOPT_CONNECTTIMEOUTでオーバーライドしない限り、CURLはdefault_socket_timeoutに従います。

$socket_timeout = ini_get('default_socket_timeout'); // timeout in seconds