PHP

PHP OAuth2 Social Login

Implement Google, GitHub, and Facebook social login using OAuth2 authorization flow.

PHPOAuth2Social LoginAPI

Thumbnail for PHP OAuth2 Social Login

Overview

Implement Google, GitHub, and Facebook social login using OAuth2 authorization flow.

Key Concepts

This project covers essential PHP development patterns including object-oriented programming, database interaction, and security best practices.

Getting Started

bash
# Clone the repository
git clone https://github.com/example/php-13-php-oauth2-social-login
cd php-13-php-oauth2-social-login

# Start local server
php -S localhost:8000

Core Implementation

php
<?php
declare(strict_types=1);

namespace App;

class PHPService
{
    private \PDO $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function findAll(): array
    {
        $stmt = $this->db->query("SELECT * FROM items ORDER BY created_at DESC");
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO items (title, content, status) VALUES (:title, :content, :status)"
        );
        $stmt->execute([
            ':title'   => htmlspecialchars($data['title']),
            ':content' => htmlspecialchars($data['content']),
            ':status'  => $data['status'] ?? 'draft',
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function update(int $id, array $data): bool
    {
        $stmt = $this->db->prepare(
            "UPDATE items SET title = :title, content = :content WHERE id = :id"
        );
        return $stmt->execute([
            ':id'      => $id,
            ':title'   => htmlspecialchars($data['title']),
            ':content' => htmlspecialchars($data['content']),
        ]);
    }
}
?>

Database Schema

sql
CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    status ENUM('draft', 'published', 'archived') DEFAULT 'draft',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Security Considerations

- All user inputs are sanitized with \htmlspecialchars()\ - Database queries use prepared statements to prevent SQL injection - CSRF tokens are validated on all form submissions - Sessions are configured with \httponly\ and \secure\ flags

Tags

- PHP - OAuth2 - Social Login - API

Related Projects

Comments (0)

Leave a Comment

No comments yet. Be the first to comment!