LoginSignup
3
7

More than 5 years have passed since last update.

PHPでFacebook認証

Posted at

随分躓いたFacebook認証。
何より、ググっても言語やversion等環境が違う記事が多く、詳細が分かってないと対処できない。こういう時は本を買って丸コピするのが得策だが、それもなんか見つからない。

斯く斯く然々で、出来たのでメモっておく。
ログインボタンが置いてあるページからリダイレクトされるphpファイルを書きます。ログインしないと入れないかどうかは分岐で調整してください。


session_start(); //サーバ側で保存する情報$_SESSIONを使用します宣言

if(empty($_GET[code])){ //初めてこのページに来た人は?code=が空なので以下の処理を実行
 $_SESSION[state] = sha1(uniqid(mt_rand(), true)); //乱数な接頭辞を付けたユニークIDをハッシュ化して予測不能な値を作る
 $params = array(
  client_id => FacebookアプリID,
  redirect_uri=> http://xxx.com/redirect.php, //このファイルの場所
  state => $_SESSION[state], //sessionにも入れた予測不能な値を入れる
  scope => public_profile,user_friends,email //Facebookから取得したいもの、申請しないで取得できるのは左記3つ
 );
 $url = "https://www.facebook.com/dialog/oauth?".http_build_query($params); //このあとぶっとぶAPIのURL準備
 header(Location: .$url); //飛ぶ
 exit; //飛ばした場合はここで終了。戻ってきたときは?code=が空でないのでelseに分岐する
}
else{ //$_GET[‘code’]が空ではない場合
 if($_SESSION[state] != $_GET[state]){
 echo "不正アクセスの可能性があるので終了"
exit;
}
$params = array(
client_id => FacebookアプリID,
client_secret => FacebookアプリSecret,
code => $_GET[code], //戻ってきたコード
redirect_uri => http://xxx.com/redirect.php //このファイルの場所
);
$url = https://graph.facebook.com/oauth/access_token?.http_build_query($params); //apiのurlにparamsをくっつけて渡す
$body = file_get_contents($url); // access_token=xxxx みたいに返ってくる
parse_str($body); //パースして$access_tokenつくる
$url = https://graph.facebook.com/me?access_token=.$access_token.&fields=name,picture,email; //トークンを渡して、名前、プロフィール画像、メアドを取得
$me = json_decode(file_get_contents($url)); //jsonで返ってくるのでデコード

try { //データベースに接続(DB事前準備は割愛)
 $dbh = new PDO(mysql:host=localhost;dbname=データベース名,ユーザー名,パスワード);
} catch(PDOException $e){
 echo $e->getMessage();
 exit;
}
//新規ユーザーかどうかFBIDを使って確認
$stmt = $dbh ->prepare("select * from users where facebook_user_id=:user_id limit 1");
$stmt->execute(array(":user_id"=>$me->id));
$user = $stmt->fetch();

if(empty($user)){ //新規ユーザーなら登録
 $stmt = $dbh->prepare("insert into users (facebook_user_id, facebook_name, facebook_picture, facebook_access_token, created, modified, facebook_email) values (:user_id, :name, :picture, :access_token, now(), now(), :email);");
 $params = array(
 ":user_id"=>$me->id,
 ":name"=>$me->name,
 ":picture"=>$me->picture->data->url,
 ":access_token"=>$access_token,
 ":email"=>$me->email
);
$stmt->execute($params);
$stmt = $dbh->prepare("select * from users where id=:last_insert_id limit 1");
$stmt->execute(array(":last_insert_id"=>$dbh->lastInsertId())); //最後に挿入されたIDのユーザー名
$user = $stmt->fetch();
}
if(!empty($user)){ //ちゃんと登録済を確認できたor新規登録できた場合
 session_regenerate_id(true); //元々のsessionを消して新しく生成
 $_SESSION[user] = $user;
 header(Location: 戻したいページ);
}

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