
Below is a simple example of a PHP script that demonstrates how to implement a basic user ban system. This example will include a database table for users, and you’ll see how to ban a user by updating their status in the database.
Step 1: Set up your database
First, create a database and a table to hold the user data. Here’s an example SQL statement to create a simple users
table:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, is_banned TINYINT(1) DEFAULT 0 );
Step 2: PHP script to ban a user
Next, here’s a ban_user.php
script that takes a username and bans that user by updating the is_banned
field in the database.
<?php // Database connection details $host = 'localhost'; $db = 'your_database_name'; $user = 'your_database_user'; $pass = 'your_database_password'; $charset = 'utf8mb4'; // Set up the PDO connection $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); } // Function to ban a user function banUser($username, $pdo) { $sql = "UPDATE users SET is_banned = 1 WHERE username = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$username]); if ($stmt->rowCount() > 0) { echo "User '$username' has been banned successfully."; } else { echo "User '$username' not found or already banned."; } } // Check if a username is provided if (isset($_POST['username'])) { $username = $_POST['username']; // Call the function to ban the user banUser($username, $pdo); } ?> <!DOCTYPE html> <html> <head> <title>Ban User</title> </head> <body> <h1>Ban a User</h1> <form method="post"> <label for="username">Username:</label> <input type="text" name="username" required> <button type="submit">Ban User</button> </form> </body> </html>
How it works
- Database Connection: The script first sets up a connection to the MySQL database using PDO.
- Ban User Function: The
banUser
function takes a username and updates theis_banned
field to1
(true) in the database if the user exists. - HTML Form: The user is prompted to enter a username, which is then sent to the server via a POST request.
- Execution: When the form is submitted, the script checks if a username is provided and calls the
banUser
function.
Notes
- Make sure you replace the database connection details (name, user, password) with your actual values.
- This script does not include any security measures (like user authentication, validation, or sanitization), which should be implemented in a production environment.
- You might also want to handle unbanning users and display a list of banned users for better management.