Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Start session
- session_start();
- // Rate limiting function for IP address
- function rateLimiter($maxRequests = 100, $timeFrame = 60) {
- $ip = $_SERVER['REMOTE_ADDR'];
- $currentTime = time();
- // Create or load the requests tracking file
- $file = "requests.json";
- $requests = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
- // Remove outdated records
- if (isset($requests[$ip]) && $currentTime - $requests[$ip]['start'] > $timeFrame) {
- unset($requests[$ip]);
- }
- // Update request count
- if (!isset($requests[$ip])) {
- $requests[$ip] = ['count' => 1, 'start' => $currentTime];
- } else {
- $requests[$ip]['count']++;
- }
- file_put_contents($file, json_encode($requests));
- // Block access if the limit is exceeded
- if ($requests[$ip]['count'] > $maxRequests) {
- header("HTTP/1.1 429 Too Many Requests");
- die("Too many requests. Please try again later.");
- }
- }
- // Activate the rate limiter
- rateLimiter(100, 60); // 100 requests within 60 seconds
- // Function to sanitize input data
- function sanitizeInput($data) {
- return htmlspecialchars(strip_tags($data), ENT_QUOTES, 'UTF-8');
- }
- // Protection against SQL injection
- function secureDatabaseQuery($conn, $query, $params) {
- $stmt = $conn->prepare($query);
- $stmt->execute($params);
- return $stmt;
- }
- // Limit login attempts
- if (!isset($_SESSION['login_attempts'])) {
- $_SESSION['login_attempts'] = 0;
- }
- if ($_SESSION['login_attempts'] >= 5) {
- die("Too many login attempts. Please try again later.");
- }
- // Example login
- if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- $username = sanitizeInput($_POST['username']);
- $password = sanitizeInput($_POST['password']);
- // Login check
- if ($username === 'admin' && $password === 'password123') {
- echo "Welcome, $username!";
- $_SESSION['login_attempts'] = 0;
- } else {
- $_SESSION['login_attempts']++;
- echo "Invalid username or password.";
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement