Build a User Web App from Scratch with Vanilla PHP 8+

 




Building a user web app from scratch with vanilla PHP 8+ involves several key steps, from setting up your environment to implementing authentication and building your user interface. Here’s a full outline along with sample code for each major part.

🔧 Prerequisites

  • PHP 8+ installed (use XAMPP, MAMP, or a manual install).

  • A web server (Apache or Nginx).

  • Basic knowledge of PHP, HTML, and SQL.

  • A MySQL or MariaDB database.

🗂️ Project Structure

user-app/
│
├── config/
│   └── config.php
├── includes/
│   └── db.php
│   └── functions.php
├── public/
│   ├── index.php
│   ├── register.php
│   ├── login.php
│   ├── logout.php
│   └── dashboard.php
└── sql/
    └── schema.sql

1. ✅ Setup Database

sql/schema.sql

CREATE DATABASE user_app;

USE user_app;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2. ⚙️ Configuration Files

config/config.php

<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user_app');
define('DB_USER', 'root');
define('DB_PASS', ''); // set your root password if needed

includes/db.php

<?php
require_once __DIR__ . '/../config/config.php';

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

includes/functions.php

<?php
session_start();

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function redirectIfNotLoggedIn() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit;
    }
}

3. 👤 Registration Page

public/register.php

<?php
require_once '../includes/db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $email    = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");

    try {
        $stmt->execute([$username, $email, $password]);
        header('Location: login.php');
    } catch (PDOException $e) {
        $error = "Registration failed: " . $e->getMessage();
    }
}
?>

<form method="post">
    <input name="username" required placeholder="Username">
    <input name="email" required type="email" placeholder="Email">
    <input name="password" required type="password" placeholder="Password">
    <button type="submit">Register</button>
    <?php if (isset($error)) echo "<p>$error</p>"; ?>
</form>

4. 🔐 Login Page

public/login.php

<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        header('Location: dashboard.php');
    } else {
        $error = "Invalid credentials";
    }
}
?>

<form method="post">
    <input name="email" required type="email" placeholder="Email">
    <input name="password" required type="password" placeholder="Password">
    <button type="submit">Login</button>
    <?php if (isset($error)) echo "<p>$error</p>"; ?>
</form>

5. 🧾 Dashboard (Protected Page)

public/dashboard.php

<?php
require_once '../includes/functions.php';
redirectIfNotLoggedIn();
?>

<h1>Welcome, <?= htmlspecialchars($_SESSION['username']) ?>!</h1>
<p><a href="logout.php">Logout</a></p>

6. 🚪 Logout

public/logout.php

<?php
session_start();
session_destroy();
header('Location: login.php');
exit;

✅ Final Touches

  • Add HTML templates or integrate a frontend framework (like Bootstrap).

  • Add CSRF protection.

  • Add email verification and password reset if needed.

  • Secure cookies and sessions (use session.cookie_secure, httponly, etc.).


Post a Comment

0 Comments