What are the potential benefits of using a MySQL database for IP banning in PHP?
Issue: When implementing IP banning in PHP, it is important to efficiently store and manage the list of banned IP addresses. Using a MySQL database can provide a scalable and organized solution for storing and querying banned IPs.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "banned_ips";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Function to check if an IP is banned
function isBannedIP($ip) {
global $conn;
$sql = "SELECT * FROM banned_ips WHERE ip_address = '$ip'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
}
// Usage
$ip = $_SERVER['REMOTE_ADDR'];
if (isBannedIP($ip)) {
echo "Access denied.";
} else {
echo "Access granted.";
}
// Close MySQL connection
$conn->close();
Keywords
Related Questions
- How can one prevent long strings from distorting the layout in PHP when displaying text from a database within a table?
- What are the potential drawbacks of using elseif statements in PHP setup scripts for managing sequential steps?
- What are the advantages of using a database for managing voting data in PHP?