Creating a Secure PHP Login System with Bootstrap 5, Database, and CSS
Creating a Secure PHP Login System with Bootstrap 5, Database, and CSS

Creating a secure login system is a crucial part of any web application. This tutorial will guide you through the process of building a secure PHP login system using Bootstrap 5 for styling, a MySQL database for user data storage, and CSS animations for a smooth user experience. Prerequisites Before we start, ensure you have the following: A web server with PHP and MySQL installed (e.g., XAMPP, WAMP, LAMP). Basic knowledge of PHP, MySQL, HTML, and CSS. Bootstrap 5 library. Step 1: Setting Up the Project Create the project directory structure: secure-login/ ├── css/ │ └── styles.css ├── js/ ├── index.php ├── login.php ├── register.php ├── welcome.php └── config.php   Download and include Bootstrap 5: Add the following Bootstrap CDN links in your index.php, login.php, register.php, and welcome.php files: <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> Create a database and user table: CREATE DATABASE secure_login; USE secure_login; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );   Step 2: Configuration File Create config.php to handle database connections: <?php $servername = "localhost"; $username = "root"; // DB username $password = "root"; // DB password $dbname = "secure_login"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?> Step 3: Registration Form Create register.php for new users to sign up: <?php require_once "config.php"; $username = $password = ""; $username_err = $password_err = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty(trim($_POST["username"]))) { $username_err = "Please enter a username."; } else { $sql = "SELECT id FROM users WHERE username = ?"; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param("s", $param_username); $param_username = trim($_POST["username"]); if ($stmt->execute()) { $stmt->store_result(); if ($stmt->num_rows == 1) { $username_err = "This username is already taken."; } else { $username = trim($_POST["username"]); } } else { echo "Oops! Something went wrong. Please try again later."; } $stmt->close(); } } if (empty(trim($_POST["password"]))) { $password_err = "Please enter a password."; } else { $password = trim($_POST["password"]); } if (empty($username_err) && empty($password_err)) { $sql = "INSERT INTO users (username, password) VALUES (?, ?)"; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param("ss", $param_username, $param_password); $param_username = $username; $param_password = password_hash($password, PASSWORD_DEFAULT); if ($stmt->execute()) { header("location: login.php"); } else { echo "Something went wrong. Please try again later."; } $stmt->close(); } } $conn->close(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div class="wrapper"> <h2>Register</h2> <p>Please fill this form to create an account.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username</label> <input type="text" name="username" class="form-control" value="<?php echo $username; ?>"> <span class="help-block"><?php echo $username_err; ?></span> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password</label> <input type="password" name="password" class="form-control"> <span class="help-block"><?php echo $password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit"> </div> <p>Already have an account? <a href="login.php">Login here</a>.</p> </form> </div> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script> </body> </html>   Step 4: Login Form Create login.php for user authentication: <?php session_start(); require_once "config.php"; $username = $password = ""; $username_err = $password_err = $login_err = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty(trim($_POST["username"]))) { $username_err = "Please enter username."; } else { $username = trim($_POST["username"]); } if (empty(trim($_POST["password"]))) { $password_err = "Please enter your password."; } else { $password = trim($_POST["password"]); } if (empty($username_err) && empty($password_err)) { $sql = "SELECT id, username, password FROM users WHERE username = ?"; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param("s", $param_username); $param_username = $username; if ($stmt->execute()) { $stmt->store_result(); if ($stmt->num_rows == 1) { $stmt->bind_result($id, $username, $hashed_password); if ($stmt->fetch()) { if (password_verify($password, $hashed_password)) { session_start(); $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; header("location: welcome.php"); } else { $login_err = "Invalid username or password."; } } } else { $login_err = "Invalid username or password."; } } else { echo "Oops! Something went wrong. Please try again later."; } $stmt->close(); } } $conn->close(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div class="wrapper"> <h2>Login</h2> <p>Please fill in your credentials to login.</p> <?php if(!empty($login_err)){ echo '<div class="alert alert-danger">' . $login_err . '</div>'; } ?> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username</label> <input type="text" name="username" class="form-control" value="<?php echo $username; ?>"> <span class="help-block"><?php echo $username_err; ?></span> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password</label> <input type="password" name="password" class="form-control"> <span class="help-block"><?php echo $password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> <p>Don't have an account? <a href="register.php">Sign up now</a>.</p> </form> </div> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script> </body> </html>   Step 5: Welcome Page Create welcome.php to display after successful login: <?php session_start(); if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: login.php"); exit; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"></head> <body> <div class="page-header"> <h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1> </div> <p> <a href="logout.php" class="btn btn-danger">Sign Out of Your Account</a> </p> <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script> </body> </html> Step 6: CSS Animations Add CSS animations in styles.css: body { font: 14px sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f8f9fa; } .wrapper { width: 360px; padding: 20px; background: #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); animation: fadeIn 1.5s ease-in-out; } @keyframes fadeIn { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } } Step 7: Logout Create logout.php to handle user logout: <?php session_start(); $_SESSION = array(); session_destroy(); header("location: login.php"); exit; ?>   You've now created a secure PHP login system with Bootstrap 5, MySQL, and CSS animations. This setup provides a basic structure that you can expand upon by adding more features such as email verification, password recovery, and user profile management. Remember to always prioritize security and follow best practices to protect user data.  

Converting Hex Colors to Dark, Light Versions, and RGB Using PHP
Converting Hex Colors to Dark, Light Versions, and RGB Using PHP

When developing web applications, manipulating colors is often necessary to create dynamic and visually appealing designs. PHP can be a handy tool for converting hex colors to their darker or lighter versions and RGB format. This article will guide you through the process of achieving these tasks using PHP. Understanding Hex and RGB Colors Colors in web development are typically represented using hex (hexadecimal) or RGB (Red, Green, Blue) formats. Hex Color: Represented as a six-digit combination of numbers and letters preceded by a hash (#), for example, #FF5733. RGB Color: Represented as a function rgb() with three parameters, each ranging from 0 to 255, for example, rgb(255, 87, 51).   Converting Hex to RGB Before manipulating the color, it's essential to convert the hex color to RGB format. This process involves extracting the red, green, and blue components from the hex string. Here’s a function to convert a hex color to RGB: function hexToRgb($hex) { $hex = str_replace("#", "", $hex); if(strlen($hex) == 3) { $r = hexdec(str_repeat(substr($hex, 0, 1), 2)); $g = hexdec(str_repeat(substr($hex, 1, 1), 2)); $b = hexdec(str_repeat(substr($hex, 2, 1), 2)); } else { $r = hexdec(substr($hex, 0, 2)); $g = hexdec(substr($hex, 2, 2)); $b = hexdec(substr($hex, 4, 2)); } return array($r, $g, $b); } Example Usage: $hex = "#FF5733"; $rgb = hexToRgb($hex); print_r($rgb); // Output: Array ( [0] => 255 [1] => 87 [2] => 51 )   Converting Hex to a Darker Version To darken a color, you reduce its RGB values. Here's a function to darken a hex color by a specific percentage: function darkenHex($hex, $percent) { $rgb = hexToRgb($hex); $r = max(0, min(255, $rgb[0] - ($rgb[0] * $percent / 100))); $g = max(0, min(255, $rgb[1] - ($rgb[1] * $percent / 100))); $b = max(0, min(255, $rgb[2] - ($rgb[2] * $percent / 100))); return sprintf("#%02x%02x%02x", $r, $g, $b); } Example Usage: $hex = "#FF5733"; $darkHex = darkenHex($hex, 20); echo $darkHex; // Output: #cc4629 Converting Hex to a Lighter Version To lighten a color, you increase its RGB values. Here’s a function to lighten a hex color by a specific percentage: function lightenHex($hex, $percent) { $rgb = hexToRgb($hex); $r = max(0, min(255, $rgb[0] + ($rgb[0] * $percent / 100))); $g = max(0, min(255, $rgb[1] + ($rgb[1] * $percent / 100))); $b = max(0, min(255, $rgb[2] + ($rgb[2] * $percent / 100))); return sprintf("#%02x%02x%02x", $r, $g, $b); } Example Usage: $hex = "#FF5733"; $lightHex = lightenHex($hex, 20); echo $lightHex; // Output: #ff9177   Combining the Functions Combining all the functions, you can create a utility class to manage color conversions and adjustments. class ColorConverter { public static function hexToRgb($hex) { $hex = str_replace("#", "", $hex); if(strlen($hex) == 3) { $r = hexdec(str_repeat(substr($hex, 0, 1), 2)); $g = hexdec(str_repeat(substr($hex, 1, 1), 2)); $b = hexdec(str_repeat(substr($hex, 2, 1), 2)); } else { $r = hexdec(substr($hex, 0, 2)); $g = hexdec(substr($hex, 2, 2)); $b = hexdec(substr($hex, 4, 2)); } return array($r, $g, $b); } public static function darkenHex($hex, $percent) { $rgb = self::hexToRgb($hex); $r = max(0, min(255, $rgb[0] - ($rgb[0] * $percent / 100))); $g = max(0, min(255, $rgb[1] - ($rgb[1] * $percent / 100))); $b = max(0, min(255, $rgb[2] - ($rgb[2] * $percent / 100))); return sprintf("#%02x%02x%02x", $r, $g, $b); } public static function lightenHex($hex, $percent) { $rgb = self::hexToRgb($hex); $r = max(0, min(255, $rgb[0] + ($rgb[0] * $percent / 100))); $g = max(0, min(255, $rgb[1] + ($rgb[1] * $percent / 100))); $b = max(0, min(255, $rgb[2] + ($rgb[2] * $percent / 100))); return sprintf("#%02x%02x%02x", $r, $g, $b); } } $hex = "#FF5733"; $rgb = ColorConverter::hexToRgb($hex); $darkHex = ColorConverter::darkenHex($hex, 20); $lightHex = ColorConverter::lightenHex($hex, 20); echo "Original Hex: $hex\n"; echo "RGB: " . implode(", ", $rgb) . "\n"; echo "Darker Hex: $darkHex\n"; echo "Lighter Hex: $lightHex\n";  

How to Create a Dynamic Sitemap with PHP and a Database
How to Create a Dynamic Sitemap with PHP and a Database

Creating a dynamic sitemap for your website is crucial for search engine optimization (SEO) and improving the discoverability of your content. In this tutorial, we'll walk through the process of generating a sitemap using PHP and a MySQL database. This guide assumes you have a basic understanding of PHP and MySQL. Step 1: Set Up Your Database First, ensure your database is properly set up with the necessary tables. For this example, we'll assume you have a table named pages with columns id, title, url, and last_modified.   CREATE TABLE `pages` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `title` VARCHAR(255) NOT NULL, `url` VARCHAR(255) NOT NULL, `last_modified` DATETIME NOT NULL );   Step 2: Connect to Your Database Create a PHP script to connect to your MySQL database. Save this file as db_connect.php.   <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?> Replace localhost, username, password, and database_name with your actual database credentials. Step 3: Fetch Data from the Database Next, we'll write a script to fetch the data from the pages table. Save this file as fetch_pages.php.   <?php include 'db_connect.php'; $sql = "SELECT url, last_modified FROM pages"; $result = $conn->query($sql); $pages = array(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $pages[] = $row; } } else { echo "0 results"; } $conn->close(); ?> Step 4: Generate the Sitemap Now we'll create the sitemap. Save this file as sitemap.php.   <?php include 'fetch_pages.php'; header("Content-Type: application/xml; charset=utf-8"); echo '<?xml version="1.0" encoding="UTF-8"?>'; echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; foreach ($pages as $page) { echo '<url>'; echo '<loc>' . htmlspecialchars($page['url']) . '</loc>'; echo '<lastmod>' . date('c', strtotime($page['last_modified'])) . '</lastmod>'; echo '<changefreq>weekly</changefreq>'; echo '<priority>0.8</priority>'; echo '</url>'; } echo '</urlset>'; ?>   This script will generate an XML sitemap in the proper format for search engines to read. The date('c', strtotime($page['last_modified'])) function formats the last modified date in the correct ISO 8601 format. Step 5: Access Your Sitemap Once everything is set up, you can access your sitemap by navigating to sitemap.php in your browser. For example, if your website is hosted at http://example.com, go to http://example.com/sitemap.php to see your dynamically generated sitemap.   By following these steps, you can create a dynamic sitemap using PHP and a MySQL database. This sitemap will help search engines crawl and index your website more effectively, ultimately improving your site's SEO. Regularly updating your database with new or modified content will ensure your sitemap stays current, providing search engines with the latest information about your website.   Further Enhancements Error Handling: Improve the scripts with better error handling for database connections and queries. Pagination: If your website has a large number of pages, consider implementing pagination in your sitemap to adhere to the maximum URL limits. SEO Optimization: Adjust the changefreq and priority values based on the importance and update frequency of your pages.   By maintaining an up-to-date and dynamic sitemap, you can significantly enhance your website’s visibility and performance in search engine rankings.

Creating PHP Sitemaps: A Step-by-Step Guide
Creating PHP Sitemaps: A Step-by-Step Guide

A sitemap is an essential component of a website, providing a structured list of pages to help search engines index your site more effectively. Creating a sitemap in PHP is a straightforward process that can be customized to fit your website's specific needs. In this step-by-step guide, we'll walk you through creating a PHP sitemap from scratch. What is a Sitemap? A sitemap is an XML file that lists the URLs of a website, allowing search engines like Google to crawl and index the content more efficiently. It includes additional metadata such as the last modification date, change frequency, and priority of the URLs.   Step 1: Setup Your Environment Before you start, ensure you have the following: A web server with PHP installed (such as Apache or Nginx) Access to your website's root directory A code editor (like Visual Studio Code or Sublime Text)   Step 2: Create the PHP Script   Open your code editor and create a new PHP file. Name it sitemap.php. This script will generate the sitemap XML dynamically. <?php // Define your website's base URL $base_url = "https://www.example.com/"; // Define the array of URLs to include in the sitemap $urls = [ ['loc' => '', 'lastmod' => '2023-06-08', 'changefreq' => 'daily', 'priority' => '1.0'], ['loc' => 'about', 'lastmod' => '2023-06-07', 'changefreq' => 'monthly', 'priority' => '0.8'], ['loc' => 'contact', 'lastmod' => '2023-06-06', 'changefreq' => 'yearly', 'priority' => '0.5'], // Add more URLs as needed ]; // Function to generate XML sitemap function generateSitemap($base_url, $urls) { // Create a new DOMDocument object $dom = new DOMDocument('1.0', 'UTF-8'); // Create the <urlset> root element and add namespace attributes $urlset = $dom->createElement('urlset'); $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); $dom->appendChild($urlset); // Loop through each URL and add it to the sitemap foreach ($urls as $url) { $url_element = $dom->createElement('url'); // Add <loc> element $loc = $dom->createElement('loc', htmlspecialchars($base_url . $url['loc'])); $url_element->appendChild($loc); // Add <lastmod> element $lastmod = $dom->createElement('lastmod', $url['lastmod']); $url_element->appendChild($lastmod); // Add <changefreq> element $changefreq = $dom->createElement('changefreq', $url['changefreq']); $url_element->appendChild($changefreq); // Add <priority> element $priority = $dom->createElement('priority', $url['priority']); $url_element->appendChild($priority); // Append the <url> element to <urlset> $urlset->appendChild($url_element); } // Set the content type to XML and output the XML content header('Content-Type: application/xml'); echo $dom->saveXML(); } // Call the function to generate the sitemap generateSitemap($base_url, $urls); ?>   Step 3: Customize Your URLs In the $urls array, add the URLs of your website. Each URL is an associative array with four keys: loc: The URL path relative to the base URL. lastmod: The date when the page was last modified. changefreq: How frequently the page is likely to change (e.g., daily, monthly, yearly). priority: The priority of the page relative to other pages on the site (a value between 0.0 and 1.0). Customize these values according to your website's structure and content update frequency.   Step 4: Upload and Test Your Sitemap Upload sitemap.php to your website's root directory. Access the sitemap by navigating to https://www.example.com/sitemap.php in your browser. If everything is set up correctly, you should see an XML file listing your website's URLs.   Step 5: Submit Your Sitemap to Search Engines To help search engines index your website more effectively, submit your sitemap to services like Google Search Console and Bing Webmaster Tools. This ensures that search engines are aware of your sitemap and can crawl your site accordingly.   Submitting to Google Search Console Log in to Google Search Console. Select your website. Go to the Sitemaps section under the Index menu. Enter the URL of your sitemap (e.g., https://www.example.com/sitemap.php) and click Submit. Submitting to Bing Webmaster Tools Log in to Bing Webmaster Tools. Select your website. Go to the Sitemaps section under the Configure My Site menu. Enter the URL of your sitemap and click Submit.   Creating a sitemap in PHP is a straightforward process that can significantly improve your website's SEO by helping search engines index your content more efficiently.  


© vladoivankovic.com

VladoIvankovic