LoginSignup
4
3

More than 3 years have passed since last update.

PHPでcURL

Last updated at Posted at 2019-06-09

body取得

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// exec時に出力させない
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// リダイレクト許可
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);// 最大リダイレクト数
$body = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

ダウンロード

CURLOPT_RETURNTRANSFERは指定してはだめ

$tempFilePath = tempnam(sys_get_temp_dir(), 'download_');
$fp = fopen($tempFilePath, 'w');
if ($fp === false)
{
    throw new \RuntimeException('失敗');
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$result = curl_exec($ch);
fclose($fp);
curl_close($ch);

if ($result === false)
{
    throw new \RuntimeException('失敗');
}

その他

retry

curlコマンドの--retryオプションは?

無いようなのでエラーで判定したり

FTP

以下を気にする

CURLOPT_FTP_USE_EPRT
CURLOPT_FTP_USE_EPSV

Cookie

以下を気にする

CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR

POST

以下を気にする

CURLOPT_POST
CURLOPT_POSTFIELDS ※http_build_queryを行ってから送る

ファイルを送る場合はCURLFileを使う

GETとPOST以外やGETでbodyを送る

以下を気にする

CURLOPT_CUSTOMREQUEST
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3