# Secure PHP Login System

A secure, production-ready PHP login system with modern security best practices.

## Features

- **Secure Password Hashing**: Uses PHP's `password_hash()` with bcrypt
- **CSRF Protection**: Cross-Site Request Forgery tokens on all forms
- **SQL Injection Prevention**: Prepared statements for all database queries
- **Secure Session Management**: HttpOnly, Secure, SameSite cookies
- **Session Fixation Prevention**: Session regeneration on login
- **Input Sanitization**: All user inputs are sanitized
- **Session Timeout**: Automatic logout after 1 hour of inactivity

## Files

- `config.php` - Database configuration and security functions
- `login.php` - Login page with secure authentication
- `logout.php` - Secure logout functionality
- `dashboard.php` - Protected page example (requires login)
- `registration.php` - User registration

## Setup Instructions

### 1. Database Setup

Create a MySQL database and run the following SQL to create the accounts and users tables:

```sql
CREATE DATABASE IF NOT EXISTS your_database;
USE your_database;

CREATE TABLE IF NOT EXISTS accounts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    account_id INT NOT NULL,
    is_verified TINYINT(1) DEFAULT 0,
    verification_token VARCHAR(64),
    token_expiry DATETIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
);
```

### 2. Configure Database Connection

Edit `config.php` and update the database credentials:

```php
define('DB_HOST', 'localhost');
define('DB_USER', 'your_username');
define('DB_PASS', 'your_password');
define('DB_NAME', 'your_database');
```

### 3. Configure Postmark Email

1. Sign up for a Postmark account at https://postmarkapp.com/
2. Create a server and get your API key
3. Verify your sender email address in Postmark
4. Edit `config.php` and update the email configuration:

```php
define('POSTMARK_API_KEY', 'your_postmark_api_key');
define('POSTMARK_SENDER', 'your_verified_email@example.com');
define('FROM_NAME', 'Your App');
define('SITE_URL', 'https://yourdomain.com');
```

**Note**: Make sure the sender email is verified in your Postmark account before sending emails.

### 4. Registration Flow

The registration process works as follows:

1. User fills out the registration form (`registration.php`)
2. System creates an account and user record in the database
3. System generates a verification token and sends it to the user's email via Postmark
4. User clicks the verification link in the email (`verify.php`)
5. System verifies the token and marks the user as verified
6. User can now log in (`login.php`)

**Note**: Users cannot log in until their email is verified.

### 5. Server Requirements

- PHP 7.0 or higher
- MySQL 5.6 or higher
- Web server (Apache, Nginx, etc.)
- HTTPS enabled (required for secure cookies)
- PHP cURL extension (required for Postmark API)

### 6. Deploy

Upload all files to your web server and access `registration.php` to register a new account.

## Security Features Explained

### Password Hashing
Passwords are hashed using PHP's `password_hash()` with the bcrypt algorithm. This is much more secure than MD5 or SHA-1.

### CSRF Protection
Each form includes a CSRF token that is validated on submission to prevent cross-site request forgery attacks.

### SQL Injection Prevention
All database queries use prepared statements with parameter binding, preventing SQL injection attacks.

### Secure Sessions
- Cookies are marked as HttpOnly (prevents JavaScript access)
- Cookies are marked as Secure (only sent over HTTPS)
- SameSite policy set to Strict
- Session ID is regenerated on login to prevent session fixation

### Input Sanitization
All user inputs are sanitized using `htmlspecialchars()` to prevent XSS attacks.

## Usage

1. Navigate to `login.php`
2. Enter your username and password
3. Upon successful authentication, you'll be redirected to `dashboard.php`
4. Click "Logout" to securely end your session

## Protecting Additional Pages

To protect any page, add this at the top:

```php
<?php
require_once 'config.php';
startSecureSession();
requireLogin();
?>
```

## Important Notes

- **HTTPS is required** for the secure cookie settings to work properly
- Change the database credentials in `config.php` before deployment
- In production, implement rate limiting to prevent brute force attacks
- Consider adding email verification for new user registrations
- Implement proper error logging instead of displaying errors to users
- Regularly update PHP and MySQL to the latest secure versions

## License

This is a basic implementation for educational purposes. For production use, consider using established authentication libraries like Laravel's authentication system or Symfony Security Component.
