<手順>
①自動ログイン希望時
○ログインキー生成
・クッキーへ登録
・DBに登録
→メールアドレス&パスワードが合っていればページ遷移
②サイト訪問時
○ログインキーチェック
・クッキーをチェック
・DBで照合
→オーケーならページ遷移
①
<?php session_regenerate_id(true); $_SESSION['USER'] = $user; //リセット処理(※1) if ($auto_login) { $auto_login_key = sha1(uniqid(mt_rand(), true)); setcookie('○○○', $auto_login_key, time()+3600*24*365, '/xxxx/xxxx/xxxx/'); $sql = "insert into auto_login (user_id, c_key, expire, created_at, updated_at) values (:user_id, :c_key, :expire, now(), now())"; $stmt = $pdo->prepare($sql); $params = array( ":user_id" => $user['id'], ":c_key" => $auto_login_key, ":expire" => date('Y-m-d H:i:s', time()+3600*24*365) ); $stmt->execute($params); } header('Location:'.SITE_URL.'index.php'); unset($pdo); exit; } unset($pdo);
(※1)
if (isset($_COOKIE['○○○'])) {
$auto_login_key = $_COOKIE['○○○'];
setcookie('MYKAKUGEN', '', time()-86400, '/xxxx/xxxx/xxxx/');
$sql = "delete from auto_login where c_key = :c_key";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(":c_key" => $auto_login_key));
}
②
<?;php if (isset($_COOKIE['○○○'])) { $auto_login_key = $_COOKIE['○○○']; $sql = "select * from auto_login where c_key = :c_key and expire >= :expire limit 1"; $stmt = $pdo->prepare($sql); $stmt->execute(array(":c_key" => $auto_login_key, ":expire" => date('Y-m-d H:i:s'))); $row = $stmt->fetch(); if ($row) { $user = getUserbyUserId($row['user_id'], $pdo); session_regenerate_id(true); $_SESSION['USER'] = $user; header('Location:'.SITE_URL.'index.php'); unset($pdo);
※auto_loginテーブル
id(形式:Integer)
user_id(形式:Intege)
c_key(形式:Varchar)
expire(形式:Timestamp)
created_at(形式:Timestamp)
updated_at(形式:Timestamp)