LoginSignup
7
3

More than 5 years have passed since last update.

PHP curlでCookieを現在の送信する

Last updated at Posted at 2017-09-10

概要

現在、ブラウザで開いているページのクッキーをcurlでリクエストする際に追加したかった。
調べても、curlで連続してページを移動する場合のやり方はよくあるのですが、
現在のクッキーをセットして一度だけリクエストする方法がなかなか見つからなかったので
調べたことをメモしておく。

$_COOKIEの値を一緒に送る

$_COOKIEの値をヘッダー情報に追加してリクエストする

/**
 * 情報を取得する
 * @return array
 */
function getAuthInfo()
{
    static $auth;

    // 何度もリクエストしない対応
    if ($auth) {
        return $auth;
    }

    // header情報に追加するCookieパラメータ作成
    $cookie = [];
    foreach ($_COOKIE as $key => $val) {
        $cookie[] = $key.'='.$val.';';
    }

    // リクエスト(GET)
    $url    = 'https://' . $_SERVER['HTTP_HOST'] . '/ajax/hoge';
    $cookie = implode(' ', $cookie);
    $option = [
        CURLOPT_CUSTOMREQUEST  => 'GET',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT      => 'hoge',
        CURLOPT_TIMEOUT        => 1,
        CURLOPT_COOKIEFILE     => '',
        CURLOPT_HTTPHEADER     => [
            'Cookie: '.$cookie
        ]
    ];
    $results = httpRequest($url, $option);
    if ($results['option']['status'] === 200) {
        return $auth = json_decode($results['response'], true);
    }
    return [];
}

/**
 * Get Request (cURL)
 * ※ タイムアウトなどに問題がありそうなのでcURL版を新設
 *
 * @param   string  $url
 * @param   array   $option
 * @return  array
 */
function httpRequest($url, $option)
{
    $ch = curl_init($url);
    curl_setopt_array($ch, $option);
    $results   = curl_exec($ch);
    $error_no  = curl_errno($ch);
    $info      = curl_getinfo($ch);
    curl_close($ch);

    $status  = (isset($info['http_code'])) ? $info['http_code'] : null;
    $timeout = false;
    if ($status === 0 && $error_no === CURLE_OPERATION_TIMEDOUT) {
        $timeout = true;
    }

    return [
        'response' => $results,
        'option'   => [
            'status'  => $status,
            'timeout' => $timeout,
            'info'    => $info,
        ]
    ];
}

参考サイト

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