1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cURL関数

Posted at

初心者のため、細かいミスや違う所があったらマサカリをどんどん投げてください。
よろしくお願いいたします。

cURL関数とは

cURlとはHTTPリクエストをすることにより、外部サイトの情報を取得できる関数のことをいいます。情報を取得するというと、file_get_contentsという物もあります。大概はfile_get_contentsの方がシンプルに書けるので便利です。しかし、外部のAPIを使うためにヘッダに認証キーを乗せたり、POSTで送信したりする場合はオプションの数が多いcURLの方が自然に書くことができます。

cURLの使い方

コード例を紹介していきます。

function file_curl($url)
{
  $ch= curl_init();//(1)
  curl_setopt($ch, CURLOPT_URL, $url);//(2)
  curl_setopt($ch, CURLOPT_HEADER, false);//(2)
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//(2)
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//(2)
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);//(2)
  $html = curl_exec($ch);//(3)
  curl_close($ch);//(4)
  return $html;
}

上から見ていくとこのようになります。

1.curl_initで初期化

$ch= curl_init();

2.curl_setoptでオプション設定

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);

3.curl_execで処理実行

$html = curl_exec($ch);

4.curl_closeで終了処理

curl_close($ch);

(2)のオプションについては以下になります。

Option 意味
CURLOPT_URL CURLOPT_URL URLの指定
CURLOPT_HEADER ヘッダーの有無(false=いらない)
CURLOPT_RETURNTRANSFER データを文字列に変換するか(true=する)
CURLOPT_SSL_VERIFYPEER SSL証明書の検証をするか(false=しない)
CURLOPT_TIMEOUT タイムアウトする時間(秒)

#終わりに
cURLの本当に基本的な使い方や使う意味を紹介しました。
他のみなさんの記事や公式マニュアルを見ていると、まだまだオプションの種類もありますので参考になるURLを貼って起きます。
またより具体的な使い方を紹介していただいているサイトも貼っておきます。

公式マニュアル
http://php.net/manual/ja/book.curl.php

オプション一覧
http://jp2.php.net/curl_setopt

       
       
  
  
       
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?