Advertisement
nflcs

Protection Against Attacks

Dec 23rd, 2024
1,847
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. // Start session
  3. session_start();
  4.  
  5. // Rate limiting function for IP address
  6. function rateLimiter($maxRequests = 100, $timeFrame = 60) {
  7.     $ip = $_SERVER['REMOTE_ADDR'];
  8.    $currentTime = time();
  9.    
  10.     // Create or load the requests tracking file
  11.     $file = "requests.json";
  12.     $requests = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
  13.  
  14.     // Remove outdated records
  15.     if (isset($requests[$ip]) && $currentTime - $requests[$ip]['start'] > $timeFrame) {
  16.        unset($requests[$ip]);
  17.     }
  18.  
  19.     // Update request count
  20.     if (!isset($requests[$ip])) {
  21.         $requests[$ip] = ['count' => 1, 'start' => $currentTime];
  22.    } else {
  23.         $requests[$ip]['count']++;
  24.    }
  25.  
  26.     file_put_contents($file, json_encode($requests));
  27.  
  28.     // Block access if the limit is exceeded
  29.     if ($requests[$ip]['count'] > $maxRequests) {
  30.        header("HTTP/1.1 429 Too Many Requests");
  31.         die("Too many requests. Please try again later.");
  32.     }
  33. }
  34.  
  35. // Activate the rate limiter
  36. rateLimiter(100, 60); // 100 requests within 60 seconds
  37.  
  38. // Function to sanitize input data
  39. function sanitizeInput($data) {
  40.     return htmlspecialchars(strip_tags($data), ENT_QUOTES, 'UTF-8');
  41. }
  42.  
  43. // Protection against SQL injection
  44. function secureDatabaseQuery($conn, $query, $params) {
  45.     $stmt = $conn->prepare($query);
  46.     $stmt->execute($params);
  47.     return $stmt;
  48. }
  49.  
  50. // Limit login attempts
  51. if (!isset($_SESSION['login_attempts'])) {
  52.    $_SESSION['login_attempts'] = 0;
  53. }
  54.  
  55. if ($_SESSION['login_attempts'] >= 5) {
  56.    die("Too many login attempts. Please try again later.");
  57. }
  58.  
  59. // Example login
  60. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  61.    $username = sanitizeInput($_POST['username']);
  62.    $password = sanitizeInput($_POST['password']);
  63.    
  64.     // Login check
  65.     if ($username === 'admin' && $password === 'password123') {
  66.        echo "Welcome, $username!";
  67.         $_SESSION['login_attempts'] = 0;
  68.    } else {
  69.         $_SESSION['login_attempts']++;
  70.        echo "Invalid username or password.";
  71.     }
  72. }
  73. ?>
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement