Search the Community
Showing results for tags 'cookies'.
-
I want to make it so when the email and password and remember_me cookies expire the user is logged out but only if they originally clicked remember me, if they didn't nothing will happen. how do I go about doing that? when I enter index and the cookies expired if I clicked remember me before it then it redirects to login page. if you didn't click remember me, you don't redirect anywhere and no cookies are there. also want to make the cookie password into a hashed password or token. how can I do this? how do I alter my already written code to do this? <?php session_start(); require_once 'config.php'; if (!isset($_SESSION['email']) && isset($_COOKIE['email'], $_COOKIE['password'], $_COOKIE['remember_me'])) { $email = $_COOKIE['email']; $password = $_COOKIE['password']; $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']; if ($user['role'] === 'admin') { header("Location: admin.php"); } else { header("Location: index.php"); } exit(); } } setcookie('remember_me', '', time() - 3600, "/"); setcookie('email', '', time() - 3600, "/"); setcookie('password', '', 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; } } ?> <!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">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'])) { setcookie('remember_me', '1', time() + (60 * 60 * 24 * 30), "/"); setcookie('email', $_POST['email'], time() + (60* 60 * 24 * 30), "/"); setcookie('password', $_POST['password'], time() + (60* 60 * 24 * 30), "/"); } else { setcookie('remember_me', '', time() - 3600, "/"); setcookie('email', '', time() - 3600, "/"); setcookie('password', '', time() - 3600, "/"); } $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(); }
- 1 reply
-
- cookies
- remember me
-
(and 1 more)
Tagged with:
-
Question 1. I have a form and on submit it redirects to another site. Is it possible to open that site in a new tab instead of the same page? I have tried this js code and it doesn't seem to work. if() { $get_url = 'https://www.google.ca/'; ?> <script> window.open('<?php echo $get_url; ?>','_blank'); </script> <?php } Question 2. Is it possible to have a extend popup to another site using a unique link? Take the above google link for example. Is it possible to add new code at the end of that link url which will show a popup window or something on that google page if only visited through that link?
-
Say I have this link where I've added a product to the cart. https://www.adidas.ca/on/demandware.store/Sites-adidas-CA-Site/en_CA/Cart-Show You will see the cart empty because you're on a different computer and the cookies are unique only to the browser I'm browsing on. Basically what I'm trying to do is have products on my own site and when a user goes to buy them, it will link them directly to the cart/checkout page of that said product on that site(eg. adidas). Is something like that possible to do?
-
Hi, The 'admin' section of my website stopped working a couple of months ago and I'm just trying to fix it - I was getting an error about Session_Register being deprecated and I'm now trying to knife and fork my way around it with results from various google searches. I'm an advanced SQL user but only occasionally dabble with PHP so any help would be appreciated. So, basic set up, login page checks credentials against the DB, a session cookie is set and you're let into the admin area - my script is looping me back to the login page as my !isset is true.....because I can't figure out how to set it with the new functions! This is the login include..... <?php $host="database.lcn.com"; // Host name $username="blahblah"; // Mysql username $password="blahblah"; // Mysql password $db_name="blahblah_db"; // Database name $tbl_name="users"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['username']; $mypassword= md5($_POST['pass']); // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM users WHERE is_obv = '1' and username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" $_SESSION['username'] = $myusername; $_SESSION['pass'] = $mypassword; header("location:../admin"); } else { header("location:http://www.web.co.uk/ooops"); } ?> and this is the 'login_success' include that I include on each protected page.... <? session_start(); if(!isset($_SESSION['username'])){ header("location:http://www.web.co.uk/login"); } ?> Darren
-
Hi, I have created a webpage that so far was working using SESSIONS. As soon as the user successfully logs in, i save some variables inside a SESSION array and pass them to the mainpage.php script (or any other script that needs these variables). Now i want to implement "REMEMBER ME" feature. I know that i need to store the variables i want into a COOKIE and then access the cookie to get the variables i want. How do i restructure my code now? In case of not selecting REMEMBER ME: I check to see if a SESSION is set and i use only the SESSION variables? In case of selecting REMEMBER ME: I check to see if a cookie is set and then retrieve the variables from COOKIE array? If thats the case i will need to check every script to check this? Is there an easier way to configure it? Regards, Chris
-
How do I save or what is the syntax to save a button in a cookie? test site test I did try a header like <h3>Hello</h3> but get error with a boot5 button. <code> <?php $mp = "vids/coli.mp4"; $dall ="aaa";// echo "dall=".$dall; $uep = `<button type="button" class="btn btn-warning" onmouseover="show(0)" onmouseout="hide(0)" onclick="skip(-5000) ">0:0:0</button>`; //echo "uep=".$uep; setcookie('mp'.'$mp'.time()+30*24*60*60.); setcookie('dall'.'$dall'.time()+30*24*60*60.); setcookie('uep'.'$uep'.time()+30*24*60*60.); ?> </code> ?
-
Basically thought I got this working before and now i'm stuck. I'm setting and getting a cookie using a set function ("setRememberMeToken") and retrieving them using a get function ("getRememberMeCheck") [see functions bellow in the final box]... however when i close the browser the cookie session is lost when i reopen.. I used a browser extension called Cookie-editor in chrome to check and I see nothing saved upon reopening (cookie named "token" as it uses tokens in MYSQL DB). This is the thing, if i run (this code bellow).. it actually saves the session fine and works great... saved in a experimental file I named ~/test/test/cookithing.php. <?php include '../includes/config.php'; function setRememberMeToken($pdo, $user_id) { $token = bin2hex(random_bytes('25')); $expirationDate = time() + (86400 * 7); // <-- 7 days later setcookie("token", $token, $expirationDate, "/"); echo $_COOKIE["token"] = $token; $test = true; $to = date('Y-m-d', $expirationDate); $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);"; $stmt= $pdo->prepare($sql); $stmt->execute([$user_id, $to, sha1($token)]); } setRememberMeToken($pdo, 1); echo "<br>"; echo sha1($_COOKIE["token"]); ?> So by vising this page it works!.. however not ideal situation to be in as I need it to get to work upon login... Forgetting about the code above for s second, here is the code I use for login (ask if you need more)... if (isset($_POST['remember-me'])){ setRememberMeToken($pdo, $_SESSION["userID"] ); // <----- set token //echo "<br>"; //echo sha1($_COOKIE["token"]); } and the main functions are here:.. <?php function setRememberMeToken($pdo, $user_id) { $token = bin2hex(random_bytes('25')); $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate) setcookie("token", $token, $expirationDate, "/"); $_COOKIE["token"] = $token; $test = true; $to = date('Y-m-d', $expirationDate); $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);"; $stmt= $pdo->prepare($sql); $stmt->execute([$user_id, $to, sha1($token)]); } function getRememberMeCheck($pdo) { $stmt = $pdo->prepare(" SELECT users.name, users.user_id FROM user_token, users WHERE tokenHash = ? AND expires > NOW() AND users.user_id = user_token.user_id "); $stmt->execute([sha1($_COOKIE["token"])]); $db_query = $stmt->fetch(); if (!$db_query){ return false; } $_SESSION["loggedin"] = true; $_SESSION["username"] = $db_query['name']; $_SESSION["the_usr_id"] = $db_query['user_id']; $_SESSION["userID"] = $db_query['user_id']; // ADDED DUE TO DESCRIPTION ("PROB WILL BE OK") return true; } function isRemembered() { return isset($_COOKIE['token']); } ?> Can anyone see what I'm doing wrong.. right now I'm fairly clueless..? ____________ Edit: also, my header file contains this (see bellow) also.. include 'includes/remember_token.php'; include 'includes/count_online.php'; if (isset($_COOKIE['token'])) { getRememberMeCheck($pdo); } .. this checks if the cookie is set.