Category : Web
Googleログイン 認証 PHP-MYSQL
2026年05月01
11View
ファイル構成
google-auth/
├── composer.json
├── composer.lock
├── config.php
├── google-callback.php
├── index.php
├── login.php
├── logout.php
└── vendor/
composer インストール
Composer公式サイト- PHPがインストールされているか確認:
php -v
- Composerのインストーラーをダウンロード:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" - インストーラーのハッシュを確認:
php -r "if (hash_file('sha384', 'composer-setup.php') === '最新のハッシュ値') { echo 'OK'; } else { echo 'FAIL'; } echo PHP_EOL;" - Composerをインストール:
php composer-setup.php
- インストーラーを削除:
php -r "unlink('composer-setup.php');" - グローバルに使えるよう移動:
sudo mv composer.phar /usr/local/bin/composer
- 動作確認:
composer -v
Google APIをインストール
composer require google/apiclient
MYSQLデータベース・テーブル作成
CREATE DATABASE google_auth_demo;
USE google_auth_demo;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
auth_provider VARCHAR(50),
auth_uid VARCHAR(50),
name VARCHAR(50),
email VARCHAR(50),
picture VARCHAR(50),
create_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
index.php
<?php
session_start();
if (!isset($_SESSION['user'])) {
header('Location: login.php');
exit();
}
$user = $_SESSION['user'];
?>
<h1>Welcome <?= $user['name'] ?></h1>
<p>Email: <?= $user['email'] ?></p>
<img src="<?= $user['picture'] ?>" width="100">
<br><br>
<a href="logout.php">Logout</a>
login.php
<?php require 'config.php' ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login with Google</title>
</head>
<body>
<h2>Login with Google</h2>
<h4>Click below to login with Google</h4>
<a href="google-callback.php">
<img src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png" alt="Sign in with Google">
</a>
<br><br>
</body>
</html>
google-callback.php
- Googleサービスと連携するためのインスタンス作成、Googleコンソールに登録したURLとアプリ登録時に発行されたID、シークレットキーをインスタンスに値をセットする。
Google OAuth 設定
| 項目 | 説明 |
|---|---|
| Client ID | Google Cloudで発行 |
| Client Secret | 認証用シークレット |
| Redirect URI | 認証後の戻り先URL |
$client = new Google_Client();
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri('http://localhost/callback');
ログイン同意画面を表示。!isset($_GET['code'])): Googleの認証URLを生成し、ユーザーをリダイレクトさせる。
-
OAuth2 アクセストークン取得 & ユーザー情報取得
処理 内容 authenticate() 認証コードを使ってアクセストークンを取得 $_SESSION['access_token'] セッションにトークンを保存 setAccessToken() クライアントにトークンをセット Google_Service_Oauth2 OAuth2 サービスインスタンス生成 userinfo->get() ユーザー情報を取得 $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $token = $client->getAccessToken(); $client->setAccessToken($token); $oauth = new Google_Service_Oauth2($client); $user_info = $oauth->userinfo->get();
<?php
require_once 'config.php';
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URL);
$client->addScope('email');
$client->addScope('profile');
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
exit();
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$token = $client->getAccessToken();
$client->setAccessToken($token);
$oauth = new Google_Service_Oauth2($client);
$user_info = $oauth->userinfo->get();
// Store user information in session
$stmt = $conn->prepare("SELECT * FROM users WHERE oauth_uid = ? AND oauth_provider = 'google'");
$stmt->bind_param("s", $user_info->id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 0) {
$stmt = $conn->prepare("INSERT INTO users (oauth_provider, oauth_uid, name, email, picture) VALUES ('google', ?, ?, ?, ?)");
$stmt->bind_param("ssss", $user_info->id, $user_info->name, $user_info->email, $user_info->picture);
$stmt->execute();
$_SESSION['user'] = [
'name' => $user_info->name,
'email' => $user_info->email,
'picture' => $user_info->picture
];
}
header('Location: index.php');
exit();
}
config.php
<?php
session_start();
if(!$conn = new mysqli('localhost', 'root', '', 'google_auth_demo')) {
die("Connection failed: " . $conn->connect_error);
}
define('GOOGLE_CLIENT_ID', 'Google_クライアント_ID');
define('GOOGLE_CLIENT_SECRET', 'Google_クライアント_シークレット');
define('GOOGLE_REDIRECT_URL', 'http://127.0.0.1/google-login/google-callback.php');
?>
logout.php
session_destroy — セッションに登録されたデータを全て破棄する<?php
session_start();
session_destroy();
header('Location: login.php');
exit();
PHPデベロッパー
Mastering Typography in Web Design
06 Nov 2025
Visual Hierarchy in UI Design
13 Oct 2025
Capturing Stories Through Portraits
18 Oct 2025
Creating Immersive Travel Content
10 Sep 2025