ssscriptties Posted yesterday at 07:29 AM Share Posted yesterday at 07:29 AM my code was working jus fine yesterday but when I woke up today and tried it out it wouldn't create cookies, and I'm wondering why? <?php session_start(); require_once 'config.php'; if (!isset($_SESSION['email']) && isset($_COOKIE['email'], $_COOKIE['remember_token'])) { $email = $_COOKIE['email']; $token = $_COOKIE['remember_token']; $stmt = $conn->prepare("SELECT u.*, rt.token FROM users u INNER JOIN remember_tokens rt ON u.id = rt.user_id WHERE u.email = ? AND rt.token = ? AND rt.expires_at > NOW()"); $stmt->bind_param("ss", $email, $token); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { $user = $result->fetch_assoc(); // Set session variables $_SESSION['username'] = $user['username']; $_SESSION['email'] = $user['email']; $_SESSION['role'] = $user['role']; $_SESSION['location'] = $user['location']; $_SESSION['used_remember_me'] = true; $newToken = bin2hex(random_bytes(32)); $expiresAt = date('Y-m-d H:i:s', time() + (60 * 60 * 24 * 30)); $updateStmt = $conn->prepare("UPDATE remember_tokens SET token = ?, expires_at = ? WHERE user_id = ?"); $updateStmt->bind_param("ssi", $newToken, $expiresAt, $user['id']); $updateStmt->execute(); $updateStmt->close(); setcookie('remember_token', $newToken, time() + (60 * 60 * 24 * 30), "/", "", true, true); if ($user['role'] === 'admin') { header("Location: admin.php"); } else { header("Location: index.php"); } exit(); } else { setcookie('remember_token', '', time() - 3600, "/"); setcookie('email', '', time() - 3600, "/"); } $stmt->close(); } $errors = [ 'login' => $_SESSION['login_error'] ?? '', 'register' => $_SESSION['register_error'] ?? '' ]; $successMessage = $_SESSION['register_success'] ?? ''; $activeForm = $_SESSION['active_form'] ?? 'login'; $loginAttempts = $_SESSION['login_attempts'] ?? 0; $lockoutTime = $_SESSION['lockout_time'] ?? 0; unset($_SESSION['login_error'], $_SESSION['register_error'], $_SESSION['register_success'], $_SESSION['active_form']); function showError($error) { return !empty($error) ? "<p class='error-message'>" . htmlspecialchars($error) . "</p>" : ""; } function showSuccess($message) { return !empty($message) ? "<p class='success-message'>" . htmlspecialchars($message) . "</p>" : ""; } function isActiveForm($formName, $activeForm) { return $formName === $activeForm ? 'active' : ''; } $currentTime = time(); $remainingLockoutTime = 0; $isLocked = false; if ($loginAttempts >= 3) { if (($currentTime - $lockoutTime) < 40) { $isLocked = true; $remainingLockoutTime = 40 - ($currentTime - $lockoutTime); } else { $_SESSION['login_attempts'] = 0; $_SESSION['lockout_time'] = 0; } } ?> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f5f5; } .container { display: flex; flex-direction: column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; box-sizing: border-box; } .form-box { width: 100%; max-width: 450px; padding: 30px; background: #0061af; border-radius: 10px; display: none; margin: 10px 0; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .form-box.active { display: block; } .logo-container { text-align: center; margin-bottom: 20px; } .logo-container img { width: 120px; height: auto; } h2 { font-size: 28px; text-align: center; margin-bottom: 20px; color: white; } input, select { width: 100%; padding: 12px; border: none; outline: none; font-size: 16px; margin-bottom: 20px; border-radius: 6px; background-color: rgba(255, 255, 255, 0.9); } button { display: flex; align-items: center; justify-content: center; background-color: #f3f7fe; color: #3b82f6; border: none; cursor: pointer; border-radius: 8px; width: 100%; height: 45px; transition: 0.3s; text-decoration: none; font-size: 16px; font-weight: 600; margin-bottom: 15px; } button:hover { background-color: #3b82f6; box-shadow: 0 0 0 5px #3b83f65f; color: #fff; } .error-message { padding: 12px; background: #f8d7da; border-radius: 6px; color: #a42834; text-align: center; margin-bottom: 20px; } .success-message { padding: 12px; background: #d4edda; border-radius: 6px; color: #155724; text-align: center; margin-bottom: 20px; } .form-footer { text-align: center; color: white; margin-top: 15px; } .form-footer a { color: #aad4ff; text-decoration: none; } .form-footer a:hover { text-decoration: underline; } .sso-button { background-color: #0078d4 !important; color: white !important; } .sso-button:hover { background-color: #106ebe !important; box-shadow: 0 0 0 5px rgba(0, 120, 212, 0.3) !important; } .divider { display: flex; align-items: center; margin: 20px 0; color: white; } .divider::before, .divider::after { content: ""; flex: 1; border-bottom: 1px solid rgba(255, 255, 255, 0.3); } .divider-text { padding: 0 10px; } ::-webkit-scrollbar { width: 10px; } ::-webkit-scrollbar-track { background: #f1f1f1; } ::-webkit-scrollbar-thumb { background: #0061af; } ::-webkit-scrollbar-thumb:hover { background: #0363b1; } #countdown { padding: 12px; background: #ffeeba; border-radius: 6px; color: #856404; text-align: center; margin-bottom: 20px; font-weight: bold; } .remember-me { display: flex; align-items: center; margin-bottom: 20px; color: white; } .remember-me input { width: auto; margin-right: 10px; margin-bottom: 0; } </style> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ALnasser | Ticketing System</title> <link rel="icon" type="image/x-icon" href="alnasser.png"> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="container"> <div class="form-box <?= isActiveForm('login', $activeForm); ?>" id="login-form"> <form action="login_register.php" method="post"> <center><img width="30%" height="auto" src="alnasser_nobg.png" alt="ALnasser Logo"></center> <h2>Login</h2> <?= showError($errors['login']); ?> <button type="button" class="sso-button" onclick="window.location.href='windows_login.php'"> Sign in with Windows Domain Account </button> <div class="divider"><span class="divider-text">OR</span></div> <input type="email" name="email" placeholder="Email" required> <input type="password" name="password" placeholder="Password" required> <div class="remember-me"> <input type="checkbox" id="remember_me" name="remember_me"> <label for="remember_me">Remember me for 30 days</label> </div> <?php if ($isLocked): ?> <div id="countdown">Too many failed attempts. Please try again in <span id="time"></span> seconds.</div> <button type="submit" name="login" disabled style="cursor: not-allowed; background-color: #ccc;">Login</button> <?php else: ?> <button type="submit" name="login">Login</button> <?php endif; ?> <p class="form-footer">Don't have an account? <a href="#" onclick="showForm('register-form')">Register</a></p> </form> </div> <div class="form-box <?= isActiveForm('register', $activeForm); ?>" id="register-form"> <form action="login_register.php" method="post"> <center><img width="30%" height="auto" src="alnasser_nobg.png" alt="ALnasser Logo"></center> <h2>Register</h2> <?= showError($errors['register']); ?> <?= showSuccess($successMessage); ?> <input type="text" name="username" placeholder="Username" required> <input type="email" name="email" placeholder="Email" pattern="[a-zA-Z0-9._%+-]+@alnasser\.eg$" required> <input type="password" name="password" placeholder="Password" required> <select name="role" required> <option value="">--Select Role--</option> <option value="user">User</option> <option value="admin">Admin</option> <option value="technician">Technician</option> </select> <select name="location" required> <option value="">--Select Location--</option> <option value="Asiout">Asiout</option> <option value="Zizinia">Zizinia</option> <option value="Aswan">Aswan</option> <option value="Helwan">Helwan</option> <option value="Menia">Menia</option> <option value="Mokattam">Mokattam</option> <option value="Arcadia">Arcadia</option> <option value="October">October</option> <option value="Tagamoa">Tagamoa</option> <option value="Maadi">Maadi</option> <option value="Heliopolis">Heliopolis</option> <option value="Nasr city">Nasr city</option> <option value="Obour">Obour</option> <option value="Qena">Qena</option> <option value="Smouha">Smouha</option> <option value="Haram">Haram</option> <option value="Sohag1">Sohag1</option> <option value="Bani Suef">Bani Suef</option> <option value="Mohandseen">Mohandseen</option> <option value="Tanta">Tanta</option> <option value="Mahalla">Mahalla</option> <option value="Zaqaziq">Zaqaziq</option> <option value="Shebeen">Shebeen</option> <option value="Qusseya">Qusseya</option> <option value="Mansoura2">Mansoura2</option> <option value="Luxor">Luxor</option> <option value="Damanhor">Damanhor</option> <option value="Hadayek">Hadayek</option> <option value="Agami">Agami</option> <option value="Suez">Suez</option> <option value="Fisal">Fisal</option> <option value="ismailia">ismailia</option> <option value="Mansoura 3">Mansoura 3</option> <option value="Abas el3qad">Abas el3qad</option> <option value="mohy eldeen">mohy eldeen</option> <option value="Sohag2">Sohag2</option> <option value="Zaharaa El-Maadi">Zaharaa El-Maadi</option> <option value="Gesr Al-Suez">Gesr Al-Suez</option> <option value="Shoubra">Shoubra</option> <option value="Fayoum">Fayoum</option> <option value="Hurghada">Hurghada</option> <option value="Sharm ElSheikh">Sharm ElSheikh</option> <option value="Mashaal">Mashaal</option> <option value="Victoria">Victoria</option> <option value="Al Rehab">Al Rehab</option> <option value="Madinaty">Madinaty</option> <option value="Mall of Egypt">Mall of Egypt</option> <option value="Gardenia">Gardenia</option> <option value="Tanta 2">Tanta 2</option> <option value="Port Said">Port Said</option> <option value="Town Center Mall">Town Center Mall</option> <option value="Office">Office</option> <option value="Online">Online</option> </select> <button type="submit" name="register">Register</button> <p class="form-footer">Already have an account? <a href="#" onclick="showForm('login-form')">Login</a></p> </form> </div> </div> <script src="script.js"></script> <script> <?php if ($isLocked): ?> let remainingTime = <?= $remainingLockoutTime ?>; const countdownElement = document.getElementById('time'); function updateCountdown() { if (remainingTime > 0) { countdownElement.textContent = remainingTime; remainingTime--; setTimeout(updateCountdown, 1000); } else { window.location.reload(); } } updateCountdown(); <?php endif; ?> function showForm(formId) { document.querySelectorAll('.form-box').forEach(box => box.classList.remove('active')); document.getElementById(formId).classList.add('active'); } window.onload = function() { const activeFormId = '<?= htmlspecialchars($activeForm) ?>-form'; showForm(activeFormId); }; </script> </body> </html> <?php session_start(); require_once 'config.php'; if (isset($_POST['register'])) { $username = trim($_POST['username']); $email = trim($_POST['email']); $password_raw = $_POST['password']; $role = $_POST['role']; $location = $_POST['location']; if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) { $_SESSION['register_error'] = 'Username can only contain letters, numbers, and underscores.'; $_SESSION['active_form'] = 'register'; header("Location: login&signup.php"); exit(); } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $_SESSION['register_error'] = 'Invalid email format.'; $_SESSION['active_form'] = 'register'; header("Location: login&signup.php"); exit(); } if (!preg_match('/@alnasser\.eg$/', $email)) { $_SESSION['register_error'] = 'Only @alnasser.eg email addresses are allowed.'; $_SESSION['active_form'] = 'register'; header("Location: login&signup.php"); exit(); } if (strlen($password_raw) < 8 || !preg_match('/[A-Za-z]/', $password_raw) || !preg_match('/[0-9]/', $password_raw) || !preg_match('/[^A-Za-z0-9]/', $password_raw)) { $_SESSION['register_error'] = 'Password must be at least 8 characters long and include letters, numbers, and symbols.'; $_SESSION['active_form'] = 'register'; header("Location: login&signup.php"); exit(); } $password_hashed = password_hash($password_raw, PASSWORD_DEFAULT); $stmt = $conn->prepare("SELECT email FROM users WHERE email = ?"); $stmt->bind_param("s", $email); $stmt->execute(); $checkEmail = $stmt->get_result(); if ($checkEmail->num_rows > 0) { $_SESSION['register_error'] = 'Email is already registered.'; $_SESSION['active_form'] = 'register'; } else { $stmt = $conn->prepare("INSERT INTO users (username, email, password, role, location) VALUES (?, ?, ?, ?, ?)"); $stmt->bind_param("sssss", $username, $email, $password_hashed, $role, $location); if ($stmt->execute()) { $_SESSION['active_form'] = 'login'; $_SESSION['register_success'] = 'Registration successful! Please login.'; } else { error_log("Registration failed: " . $stmt->error); $_SESSION['register_error'] = 'Registration failed. Please try again.'; $_SESSION['active_form'] = 'register'; } } $stmt->close(); $conn->close(); header("Location: login&signup.php"); exit(); } if (isset($_POST['login'])) { $email = trim($_POST['email']); $password = $_POST['password']; $loginAttempts = $_SESSION['login_attempts'] ?? 0; $lockoutTime = $_SESSION['lockout_time'] ?? 0; $currentTime = time(); if ($loginAttempts >= 3 && ($currentTime - $lockoutTime < 40)) { $_SESSION['login_error'] = 'Account locked due to too many failed attempts. Please wait.'; $_SESSION['active_form'] = 'login'; header("Location: login&signup.php"); exit(); } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $_SESSION['login_error'] = 'Invalid email format.'; $_SESSION['active_form'] = 'login'; header("Location: login&signup.php"); exit(); } if (!preg_match('/@alnasser\.eg$/', $email)) { $_SESSION['login_error'] = 'Only @alnasser.eg email addresses are allowed.'; $_SESSION['active_form'] = 'login'; header("Location: login&signup.php"); exit(); } $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?"); $stmt->bind_param("s", $email); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { $user = $result->fetch_assoc(); if (password_verify($password, $user['password'])) { $_SESSION['username'] = $user['username']; $_SESSION['email'] = $user['email']; $_SESSION['role'] = $user['role']; $_SESSION['location'] = $user['location']; $_SESSION['login_attempts'] = 0; $_SESSION['lockout_time'] = 0; if (!empty($_POST['remember_me'])) { $token = bin2hex(random_bytes(32)); $expiresAt = date('Y-m-d H:i:s', time() + (60 * 60 * 24 * 30)); // 30 days $cleanupStmt = $conn->prepare("DELETE FROM remember_tokens WHERE user_id = ?"); $cleanupStmt->bind_param("i", $user['id']); $cleanupStmt->execute(); $cleanupStmt->close(); $tokenStmt = $conn->prepare("INSERT INTO remember_tokens (user_id, token, expires_at, created_at) VALUES (?, ?, ?, NOW())"); $tokenStmt->bind_param("iss", $user['id'], $token, $expiresAt); if ($tokenStmt->execute()) { setcookie('email', $email, time() + (60 * 60 * 24 * 30), "/", "", true, true); setcookie('remember_token', $token, time() + (60 * 60 * 24 * 30), "/", "", true, true); $_SESSION['used_remember_me'] = true; } else { error_log("Failed to store remember token: " . $tokenStmt->error); } $tokenStmt->close(); } else { setcookie('remember_token', '', time() - 3600, "/"); setcookie('email', '', time() - 3600, "/"); $cleanupStmt = $conn->prepare("DELETE FROM remember_tokens WHERE user_id = ?"); $cleanupStmt->bind_param("i", $user['id']); $cleanupStmt->execute(); $cleanupStmt->close(); $_SESSION['used_remember_me'] = false; } $stmt->close(); $conn->close(); if ($user['role'] === 'admin') { header("Location: admin.php"); } else { header("Location: index.php"); } exit(); } else { $_SESSION['login_error'] = 'Incorrect email or password.'; $_SESSION['active_form'] = 'login'; $_SESSION['login_attempts'] = $loginAttempts + 1; if ($_SESSION['login_attempts'] >= 3) { $_SESSION['lockout_time'] = $currentTime; } } } else { $_SESSION['login_error'] = 'Incorrect email or password.'; $_SESSION['active_form'] = 'login'; $_SESSION['login_attempts'] = $loginAttempts + 1; if ($_SESSION['login_attempts'] >= 3) { $_SESSION['lockout_time'] = $currentTime; } } $stmt->close(); $conn->close(); header("Location: login&signup.php"); exit(); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/329842-cookies-dont-get-created/ Share on other sites More sharing options...
ssscriptties Posted yesterday at 07:51 AM Author Share Posted yesterday at 07:51 AM for anybody wondering I fixed it I changed setcookie('email', $email, time() + (60 * 60 * 24 * 30), "/", "", true, true); to setcookie('email', $email, time() + (60 * 60 * 24 * 30), "/", "", false, true); Quote Link to comment https://forums.phpfreaks.com/topic/329842-cookies-dont-get-created/#findComment-1657104 Share on other sites More sharing options...
gizmola Posted 6 hours ago Share Posted 6 hours ago Which is a bad fix. What you did was make your site dramatically less secure, by allowing people to create cookies without going through https:// which is a really bad idea. Is this an issue that only comes up in development, perhaps because you don't have a local cert installed? When you have a problem you really have to do a better job of describing the environment under which you had a problem. 99% of the time, if you had working code and it stops working, there is an explanation for that having to do with some environmental change. One tip: on your register/login script, as with any other pure PHP scripts, you should remove the ending PHP tag. I believe that someone else explained to you on another thread, that using session variables to handle bad login attempts and lockouts is another really bad idea. People wanting to brute force won't accept a session cookie, so all that logic will have no effect on those people or their automated brute force scripting. You have to log bad attempts using some sort of persistence (typically a table related to your user table) which include the datetime/timestamp and the IP address. You can then lock out an account for a period of time, as well as locking out IP addresses that might be trying a range of different email/password combinations. You want to prevent both. Quote Link to comment https://forums.phpfreaks.com/topic/329842-cookies-dont-get-created/#findComment-1657153 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.