Jump to content

Search the Community

Showing results for 'detecting mobile device'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. 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(); } ?>
  2. here are some implementation practices - the form processing code and form should be on the same page. by putting them on separate pages, you are creating a lot of extra code. by only validating one input at a time and not having the form fields 'sticky', you are providing a poor User eXperience (UX). by storing the 'login_attempts' and 'lockout_time' in session variables, a nefarious user/bot can get unlimited new login attempts by simply not propagating the session id cookie between requests. you must store this data persistently on the server in a database table. the only user related value you should store in a session variable upon successful login is the user id (autoincrement primary index.) you should query on each page request to get any other user data, so that any changes made to the user data will take effect on the very next page request, without requiring the user to log out and back in again. the way a 'remember me' operation should be implemented is that if the remember me checkbox is checked, at the point of successfully verifying the user's credentials, generate a unique token, store that in a cookie and in a database 'remember me' table that also includes the user id, and the current datatime, for a determining token expiration. on any page request, if the remember me token cookie is set, query to find a matching row in the remember me table. if there is a row and the token is not timed out, use the user id from that row to set the session variable that identifies who the logged in user is. the rest of the code then uses this value in the session variable, just like it was set in the login form processing code. the registration process, unless being performed by an administrator, which your code is not doing, should not include the role. the role should not be something that the user can decide when they register. modern php (8+) uses exceptions for database statement errors by default - connection, query, prepare, and execute. any discrete logic you currently have testing the result of these statements should be removed since it will never get executed upon an error. both the username and email must be unique or you should only use the email and forget about a separate username. the correct way of determining if a unique value already exists in a database table is to define the column(s) as a unique index, just attempt to insert the data, and detect in the exception catch logic for the insert query if a duplicate index error (number) occurred. any form processing code should keep for the form data as a set, in an array variable, then operate on elements in this array variable throughout the rest of the code. i.e. don't write out a line of code copying every $_POST variable to a discrete variable. you need to trim ALL the user supplied inputs, mainly so that you can detect if all white-space characters were entered, before validating the data. you need to use an array to hold user/validation errors, and validate all the inputs at once, storing the errors in the array using the field name as the array index. after the end of the validation logic, if there are no errors (the array will be empty), use the submitted form data. in the login validation logic, all you really care about is that the required inputs are are not empty strings, after being trimmed. by providing additional feedback to a nefarious user/bot, you are helping narrow down the values they need to try.
  3. 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(); }
  4. if you use a cookie or the session to hold this data, it can be bypassed by simply deleting the cookie or not propagating the cookie or session id cookie between requests. you must store this data persistently on the server, in a database table. next, you are not trying to lock the account, you are preventing login attempts for an account, from a device (client type) and its location (ip). if you actually lock the account, it will allow someone to log out and lock out a legitimate user, by just making a bunch of bad login attempts for an account. once you have stored the data in a database table, on each login attempt, you would query to find if, how many, and how long ago the bad login attempts were for the account, for the device (client type) and its location (ip). If the current time is greater than the time limit you have chosen from the last bad attempt, you would process the login attempt.
  5. Absolutely, user's often don't logout intentionally, so you can't depend on that event being recorded. In general, you should be interested in any attempted change to their profile or other "escalation of privilege" or change to the core authentication mechanisms (password reset, password change). Many systems will also include and require a 2nd factor authentication at registration, which unless it's a mobile app, will typically be email. So that's another couple of event types you want to log (email authentication failure, email authentication re-request, email authentication success). Even if you are not prepared to make use of IP logging initially, I'd recommend creating the column in the table as analysis of most events you want to be concerned with (like brute force attacks) will necessitate IP logging if you want to understand where the attacks or coming from, or building in automatic countermeasures like time based IP bans.
  6. the reason for unusual operation is the ternary operator without a middle term, that the input is probably not what you expect, and php's type casting. when you leave out the middle term in the ternary operator, when the first term evaluates to true, the value used is whatever the first term is, which will be a boolean true due to the empty() statement. instead, your post method form processing code should - detect if a post method form was submitted before referencing any of the form data. detect if there is $_POST data (in case the post_max_size setting has been exceeded.) keep the form data as a set in a php array variable, then operate on elements in this array variable throughout the rest of the code. trim all the input data, mainly so that you can detect if all white-space characters were entered. validate all inputs, storing user/validation errors in an array using the field name as the array index. after the end of the validation logic, if there are no user/validation errors, use the form data. after using the form data, if there are no user/validation errors, perform a redirect to the exact same url of the current page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data should that page get browsed back to or reloaded. if you want to display a one-time success message, store it or a flag value in a session variable, then test for, display the success message, and clear the session variable at the appropriate location in the html document. if there are user/validation errors, the code will continue on to display the html document, where you will test for and display any errors, redisplay the form, populating fields with existing data, so that the user only needs to correct the invalid input(s) and can resubmit the form.
  7. PhpMailer is not sending html emails even with isHTML set to true $mail->Body = $message; $mail->isHTML(true); $mail->isHTML = true; if(!$mail->Send()) { return $mail->ErrorInfo; } Here is the html message <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Site Title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> I've tried to find a solution by searching but all everyone is saying is add $mail->isHTML(true); or $mail->isHTML = true; i have commented each out individually but still doesn't send html emails Any help at all would be much appreciated
  8. for the posted information, the requested date range of 2025-05-06 to 2025-05-22 doesn't match any of the $seasonPrices data. It starts one day after the end of the May Day range and ends one day before the start of the Summer half-term range. it should use the base/default price for every day. since you are using a standard date format, you can directly perform date comparisons by order, as mentioned in the previous thread. you can directly compare a date to the $seasonPrices SeasonStart and SeasonEnd values to find if it is between a date range. i would write a function/class-method that accepts a date input, loops over the $seasonPrices data, returns the first price that is between the SeasonStart and SeasonEnd values, or returns zero (or some other easily detected value) if it reaches the end without finding a match. as a procedural function, something like - function get_price($date,$seasonPrices) { foreach($seasonPrices as $row) { // date between start and end if($row->SeasonStart <= $date && $date <= $row->SeasonEnd) { return $row->SeasonPrice; } } // no match return 0; }
  9. telling us that something doesn't work is pointless. we are not sitting next to you and didn't see what symptom or error you got that leads you to believe something didn't work. you must tell or show us what result you got and what the expected result should be. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying all the errors it detects? have you checked in the browser's developer tools, console tab for errors? you should use 'require' for things your code must have. require/include are not functions. the () around the path/filename do nothing and should be removed. $_GET['email'] is an input to your code. it may not exist. you need to use isset() to prevent errors when it doesn't exist and you must trim, then validate it before using it, when it does exist. the two session variables are also inputs to your code. they may not exist. you need to use isset() to prevent errors when they don't exist.
  10. I am trying to include a php header file to my page but it is not working. <?php session_start(); include("header.php"); $the_email = $_GET['email']; $_SESSION['user_email'] = $the_email; ?> and header have a navbar header.php <?php session_start(); $authenticated = false; $isadmin = false; if ($_SESSION['user']) { $thename = $_SESSION['user_name']; $theimage = $_SESSION['user_photo']; $authenticated = true; $isadmin = false; } if ($_SESSION['admin']) { $thename = $_SESSION['admin_name']; $authenticated = true; $isadmin = true; } ?> <!doctype html> <html lang="en"> <head> <!-- Required Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Document Title, Description, and Author --> <title>Teacher License System</title> <meta name="description" content="Wave is a Bootstrap 5 One Page Template."> <meta name="author" content="BootstrapBrain"> <!-- Favicon and Touch Icons --> <link rel="icon" type="image/png" sizes="512x512" href="./assets/favicon/favicon-512x512.png"> <!-- Google Fonts Files --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@200;300;400;500;600;700&family=Satisfy&display=swap" rel="stylesheet"> <!-- CSS Files --> <link rel="stylesheet" href="./assets/css/wave-bsb.css"> <!-- BSB Head --> </head> <body data-bs-spy="scroll" data-bs-target="#bsb-tpl-navbar" data-bs-smooth-scroll="true" tabindex="0"> <!-- Header --> <header id="header" class="sticky-top bsb-tpl-header-sticky bsb-tpl-header-sticky-animationX"> <!-- Navbar 1 - Bootstrap Brain Component --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="index.php"> <img src="/assets/img/logo.png" width="40" height="40" class="d-inline-block align-top" alt=""> TLS CS C2&3 </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon">test</span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link text-dark" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link text-dark" href="about.php">About</a> </li> <li class="nav-item"> <a class="nav-link text-dark" href="services.php">Services</a> </li> <li class="nav-item"> <a class="nav-link text-dark" href="pricing.php">Pricing</a> </li> <li class="nav-item"> <a class="nav-link text-dark" href="contact.php">Contact US</a> </li> </ul> <?php if ($isadmin) { ?> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle text-dark" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Hello, <?= $thename ?> </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="main.php">TLS Materials</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="logout.php">Logout</a></li> </ul> </li> </ul> <?php } else if ($authenticated) { ?> <img src='/files/<?=$theimage ?>' width="75px"> <ul class="navbar-nav"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle text-dark" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"><?= $thename ?> </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="profile.php">My Profile</a></li> <li><a class="dropdown-item" href="main.php">TLS Materials</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="logout.php">Logout</a></li> </ul> </li> </ul> <?php } else {?> <ul class="navbar-nav"> <li class="navbar-item"> <a href="register.php" class="btn btn-outline-primary me-2">Register</a> </li> <li class="navbar-item"> <a href="login.php" class="btn btn-primary">Login</a> </li> </ul> <?php } ?> </div> </div> </nav> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </header> why is that? Am i missing something?
  11. the most common reason for a password_hash()/password_verify() to fail is because the database column is not long enough to hold the hashed value. another common reason are programming mistakes in the form/form processing code and a lack of server-side validation that results in the hash value not actually being from the password that was submitted in the registration code, or the value being used in the login code not being what you think it is. your post method form processing code should always trim the input data, mainly so that you can detect if all white-space characters were entered, then validate all inputs before using them.
  12. You can always check to see if session is started: <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/clearwebconfig.php'; require_once "vendor/autoload.php"; // Import the ErrorHandler and Database classes from the PhotoTech namespace. use clearwebconcepts\{ ErrorHandler, Database, LoginRepository as Login }; // Create an ErrorHandler instance $errorHandler = new ErrorHandler(); // Set the exception handler to use the ErrorHandler instance set_exception_handler([$errorHandler, 'handleException']); // Create a Database instance and establish a connection $database = new Database(); $pdo = $database->createPDO(); // Create a LoginRepository instance with the database connection $login = new Login($pdo); $checkStatus = new Login($pdo); // Start session if not already started if (session_status() == PHP_SESSION_NONE) { session_start(); } // Redirect to dashboard if the user is already logged in if ($login->check_login_token()) { header('Location: dashboard.php'); exit(); } // Generate a CSRF token if it doesn't exist and store it in the session if (!isset($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // Detect environment $isLocal = in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']); $cookieDomain = $isLocal ? '' : DOMAIN; $cookieSecure = !$isLocal; // Set to true on remote server // Process the login form submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Check if the submitted CSRF token matches the one stored in the session if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { // Sanitize the username and password input $username = strip_tags($_POST['username']); $password = $_POST['password']; // Verify the user's credentials if ($login->verify_credentials($username, $password)) { // Generate a secure login token $token = bin2hex(random_bytes(32)); // Store the login token in the database $login->store_token_in_database($_SESSION['user_id'], $token); // Set a secure cookie with the login token setcookie('login_token', $token, [ 'expires' => strtotime('+6 months'), 'path' => '/', 'domain' => $cookieDomain, // Adjusted for environment 'secure' => $cookieSecure, // Adjusted for environment 'httponly' => true, 'samesite' => 'Lax' ]); // Store the login token in the session $_SESSION['login_token'] = $token; // Redirect the user to the dashboard header('Location: dashboard.php'); exit; } else { // Log error message for invalid username or password $error = 'Invalid username or password'; error_log("Login error: " . $error); } } else { // Display an error message $error = 'Invalid CSRF token'; error_log("Login error: " . $error); $error = 'An error occurred. Please try again.'; } } // Generate a random nonce value $nonce = base64_encode(random_bytes(16)); ?> You can also make sessions persistent in your configuration and it's always best to start you session in your configuration file: session_set_cookie_params([ 'lifetime' => strtotime('+6 months'), 'path' => '/', 'domain' => 'localhost', 'secure' => false, // Since it's not HTTPS, set this to false 'httponly' => true, 'samesite' => 'Lax' ]); session_start(); ob_start(); // turn on output buffering if (empty($_SESSION['token'])) { try { $_SESSION['token'] = bin2hex(random_bytes(32)); } catch (Exception $e) { } } if (preg_match('/\.js$/', $_SERVER['REQUEST_URI'])) { return false; // Let the webserver handle JavaScript files }
  13. Hello - sincerely hoping someone out there will be able to help with this, or at least have a good idea on what's going on. I have created a 'Single Page Application' (SPA) type website, and have used PHP on the server-side. At present, nearly all my content files (XML, JPEGs, XSLT, CSS) are generated from PHP scripts. My design uses many source files, and some pages have many small images, so file caching by the client browser is very important. I have set HTTP Cache-Control response headers on everything, to inform the browser that it can and should cache everything. (Content changes get picked up when a version number changes in the URL.) So far, so good - or so I thought. My problem is that both Safari and Chrome on iOS do fresh requests of EVERYTHING that's come from PHP, every time the user opens the phone from screen-lock. So the site is fast and slick with everything loaded into cache, until a 20 second pause with the phone locked, and then everything is dog slow again the first time content is viewed. For my use-case, this is a huge usability (and server load) problem. I've noticed that this refreshing of content DOESN'T happen for regular static files. (I have a folder of static file PNG images, and these never get re-requested.) How can I make all the PHP-generated content appear to the browser to be static files, so that the browser's heuristics don't mistrust them and assume they will be changing despite the HTTP headers?????! I can't believe I'm having this problem, honestly. Never seen anything like it before, with browsers ignoring these Cache-Control directives. There's something really messed up with the logic on mobile devices....
  14. I fixed the wrong quote but there is still an error. When I put the code into Notepad++ Line 8 is a blank line under create table section. MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(3, 2, 'Virgin Bank','#000000'), (4, 3, '_Spare_2','#000000'), (5, 4, 'CT','#f' at line 8 DROP TABLE IF EXISTS `Bank_Reason`; CREATE TABLE IF NOT EXISTS `Bank_Reason` ( `ID` int(11) NOT NULL, `ReasonID` int(11) DEFAULT NULL, `Reason` varchar(20) DEFAULT NULL, `Colour` varchar(8) DEFAULT '#000000' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `Bank_Reason` -- INSERT INTO `Bank_Reason` (`ID`, `ReasonID`, `Reason`,`Colour`) VALUES (1, 0, '---SELECT','#000000'), (2, 1, 'Other',','#0000ff'), (3, 2, 'Virgin Bank','#000000'), (4, 3, '_Spare_2','#000000'), (5, 4, 'CT','#ff00ff'), (6, 5, 'Energy','#c51010'), (7, 6, 'Mobile','#27b30b'), (8, 7, 'Virgin_BB','#06b8b6'), (9, 8, 'MNOPF','#00aa00'), (10, 9, 'Water','#aa7700'), (11, 10, '@Shops','#ff0000'), (12, 11, 'Online','#7777ff'), (13, 12, 'Cash','#000000'), (14, 13, 'Pablo','#000000'), (15, 14, 'Amazon Prime','#000000'), (16, 15, 'Ebay/Paypal','#7a061c'), (17, 16, 'Argos/Store cards','#000000'), (18, 17, 'Alexa Music','#000000'), (19, 18, 'HSBC','#aa00aa'), (20, 19, 'Amazon Orders','#aa7700'), (21, 20, 'State Pension','#301de8'), (22, 21, 'Home Insurance','#000000'), (23, 22, 'Lottery','#000000'), (24, 23, 'Rent','#000000'), (25, 24, 'Private Health','#000000'), (26, 25, 'Credit card **','#000000'), (27, 26, '_Spare_1','#000000');
  15. Hi. I have an exsisting table Bank_Reason. I want to add an extra columb 'Colour' to it. I am getting an error when I try to change it. I have done a drop table and recreate. Can any help with this extra columb please. I worked fine before. P.S. I have noticed that i was missing a (`). NEW line INSERT INTO `Bank_Reason` (`ID`, `ReasonID`, `Reason`,`Colour`) VALUES. Makes no diffrence. DROP TABLE IF EXISTS `Bank_Reason`; CREATE TABLE IF NOT EXISTS `Bank_Reason` ( `ID` int(11) NOT NULL, `ReasonID` int(11) DEFAULT NULL, `Reason` varchar(20) DEFAULT NULL, `Colour` varchar(8) DEFAULT '#000000' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `Bank_Reason` -- INSERT INTO `Bank_Reason` (`ID`, `ReasonID`, `Reason`,Colour') VALUES (1, 0, '---SELECT','#000000'), (2, 1, 'Other',','#0000ff'), (3, 2, 'Virgin Bank','#000000'), (4, 3, '_Spare_2','#000000'), (5, 4, 'CT','#ff00ff'), (6, 5, 'Energy','#c51010'), (7, 6, 'Mobile','#27b30b'), (8, 7, 'Virgin_BB','#06b8b6'), (9, 8, 'MNOPF','#00aa00'), (10, 9, 'Water','#aa7700'), (11, 10, '@Shops','#ff0000'), (12, 11, 'Online','#7777ff'), (13, 12, 'Cash','#000000'), (14, 13, 'Pablo','#000000'), (15, 14, 'Amazon Prime','#000000'), (16, 15, 'Ebay/Paypal','#7a061c'), (17, 16, 'Argos/Store cards','#000000'), (18, 17, 'Alexa Music','#000000'), (19, 18, 'HSBC','#aa00aa'), (20, 19, 'Amazon Orders','#aa7700'), (21, 20, 'State Pension','#301de8'), (22, 21, 'Home Insurance','#000000'), (23, 22, 'Lottery','#000000'), (24, 23, 'Rent','#000000'), (25, 24, 'Private Health','#000000'), (26, 25, 'Credit card **','#000000'), (27, 26, '_Spare_1','#000000');
  16. @gizmola it would seem that the Software as a Service model would be more in line with my thinking (since I fear my code being co-opted). How is this best implemented? In simple terms, if the customer wants users to complete a form, would I just re-direct them to a form on MY server? Wouldn't that seem a bit suspicious if detected?
  17. The "Problems" tab is a list of problems detected by the IDE and/or various extensions. You clear the list by fixing the problems, or somehow otherwise turning off the error reporting. You can hide the tab entirely through the right-click menu on the tab area, and similarly for the problems list in the status bar.
  18. and what exactly is the problem with the last posted code? here are some points for the current code - you should use a single database extension. now that you have used the much simpler and better designed PDO extension, all your code should be updated to use the extension. you should NOT use the mysqli_real_escape_string() function, which probably doesn't have the character-set set, to match your database tables, when the connection was made, then put these pieces of data directly into the sql query statement, as this can allow sql special charters in a value to break the sql query syntax. you should use a prepared query. converting a query that has php variables being put into it into a prepared query is straight forward. if you need, someone can post a list of instructions how to do this. you should use a get method form when determining what will be displayed on a page. this is so that if someone finds a result they want to return to or share with someone, they can bookmark the URL or share the URL and be able to return to the same result. the search form should be on the same page as the result and the form should be 'sticky' and repopulate the fields, selected options, checkboxes, and radiobuttons with any existing values so that if the search doesn't find what the user expects, they can simply make changes to the search values and try again. all the search form processing code should be inside the conditional statement testing if the form has been submitted. the current code will produce a bunch of php errors and likely produce no search result and output if the page is requested without any form data. you need to trim, mainly so that you can detect if all white-space characters were entered, then validate all input data before using it. the search inputs you have shown are all 'required'. if they are not all valid, you should output error messages stating what is wrong with them and NOT run any of the query/output code. if you want to make any of these search inputs 'optional' you will need to dynamically build the WHERE part of the query and only include the terms that have search values. the use of LEFT JOIN doesn't make sense (to me). it indicates that you want to get marks data that may not have any student or school associated with it. you should just use a JOIN if you only want marks data that has school/student data. if a query doesn't match any data, you should output a message stating so, rather than outputting nothing. you need to apply htmlentities() to dynamic values being output in a html context, right before/as they are being output in order to prevent any html entities in a value from being able to break the html syntax.
  19. Thank you Mr. Barand my code is now working but want to add comments to every student so that the form master can comment about student's conduct attitude and interest fot parent to monitor students progress. The print out should also be one student per page <?php include 'session.php'; ?> <?php include '../db/dbconnect.php'; define("HOST", 'localhost'); define("USERNAME", 'root'); define("PASSWORD", ''); define("DATABASE", 'sms'); ?> <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../css/bootstrap.min.css" /> <link rel="stylesheet" href="../bootstrap-icons/font/bootstrap-icons.min.css"> <link rel="stylesheet" href="../bootstrap-icons/font/bootstrap-icons.min.css"> <link rel="stylesheet" type="text/css" href="../css/viewpasscodeadmin.css" /> <link rel="stylesheet" href="../css/report1.css"> <link rel="stylesheet" href="../font/stylesheet.css"> <link rel="stylesheet" href="../css/dataTables.bootstrap5.css" /> <link rel="stylesheet" href="../css/buttons.bootstrap5.css" /> <link rel="stylesheet" href="../css/responsive.bootstrap5.css" /> <link rel="stylesheet" href="../font/stylesheet.css"> <title>report</title> </head> <body> <div class="container"> <?php //error_reporting(0); ?> <?php if (isset($_POST['submit'])) { $acayear = mysqli_real_escape_string($con, $_POST['acayear']); $semester = mysqli_real_escape_string($con, $_POST['semester']); $form = mysqli_real_escape_string($con, $_POST['form']); $class = mysqli_real_escape_string($con, $_POST['class']); } function pdoConnect($dbname = DATABASE) { $db = new PDO("mysql:host=" . HOST . ";dbname=$dbname;charset=utf8", USERNAME, PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::MYSQL_ATTR_LOCAL_INFILE, true); return $db; } $pdo = pdoConnect(); $res = $pdo->query("SELECT school.school, school.logo, student.gender, student.program, student.house, student.image, marks.acayear, marks.semester, marks.form ,marks.class, marks.studentid, marks.name, marks.subject, marks.class_score1, marks.exam_score1,marks.total, marks.grade, marks.remarks, RANK() OVER (PARTITION BY marks.acayear, marks.semester, marks.lessonsid ORDER BY marks.total DESC) as rank FROM marks LEFT JOIN student ON marks.studentid=student.studentid LEFT JOIN school ON student.schoolid=school.schoolid WHERE marks.acayear='{$acayear}' AND marks.semester='{$semester}' AND marks.form='{$form}' AND marks.class='{$class}' ORDER BY name, subject"); $previd = 0; $tdata = ''; foreach ($res as $r) { if ($r['studentid'] != $previd) { if ($previd != 0) { // if not the first $tdata .= "\n</table>\n</div>\n</div>\n\n"; // close preceding report } $tdata .= outputReportHeading(...array_slice($r, 0, 12)); $previd = $r['studentid']; } $tdata .= outputSubject(...array_slice($r, 7)); // close last report } $tdata .= "\n</table>\n</div>\n</div>\n\n"; # # FUNCTIONS # function outputReportHeading($school, $logo, $gender, $program, $house, $image, $acayear, $semester, $form, $class, $studentid, $name) { return <<<HEAD <div class="logo1"> <img src="../uploads/student/$image" width="100px" class="rounded float-end mt-3"> </div> <div class="logo"> <img src="../uploads/logo/$logo" width="100px" class="rounded float-start mt-3"> </div> <div class="heading mt-2"> $school </div> <div class="heading2"><b> $acayear ACADEMIC YEAR</b> </div> <div class='heading2'> <b>Student ID:</b> <span class=''>$studentid</span> <b>Name of Student:</b> <span class=''>$name</span> <br> <b>Semester:</b> <span'>$semester</span> <b>House:</b> <span>$house</span> <b>Gender:</b> <span>$gender</span> <b>Program:</b> <span>$program</span> <b>Class:</b> <span>$form $class</span> </div> <div class="heading"> STUDENT TERMINAL REPORT </div> <div class="tablewrap mt-2"> <table class="table table-bordered table-sm" cellspacing="0" width="100%"> <thead> <tr class="text-center"> <th class="th-sm text-left">Subject</th> <th class="th-sm text-center">Class Score</th> <th class="th-sm text-center">Exam Score</th> <th class="th-sm text-center" >Total</th> <th class="th-sm text-center">Grade</th> <th class="th-sm text-center" >Pos</th> <th class="th-sm text-center" >Remarks</th> </tr> <thead> HEAD; } function outputSubject($semester, $form, $class, $studentid, $name, $subject, $class_score1, $exam_score1, $total, $grade, $remarks, $rank) { return <<<SUB <tbody> <tr> <td class="text-left" >$subject</td> <td class="text-center">$class_score1</td> <td class="text-center">$exam_score1</td> <td class="text-center">$total</td> <td class="text-center">$grade</td> <td class="text-center">$rank</td> <td class="text-left">$remarks</td> </tr> </div> </tbody> SUB; } ?> <?= $tdata; ?> </div>. </body> </html>
  20. Hi CBG, @mac_gyver actually posted the solution that you have chosen. And i want to say that mac_gyver and maxxd are better programmers and they have more experience than i do in this field. However, i disagree with any solutions that create a bunch of if branches because every step that a program takes can really slow it down. I definitely disagree that you cannot check it all at once. Personally, i recommend using the tools in the PHP toolbox to your advantage. I would do the following and be done with it: <?php $p = 'Yes'; $d = 'No'; $c = 'No'; $o = 'No'; $pinary = [$p] === ['Yes']; $nerror = [$d, $c, $o] === ['No','No','No']; if ($p && $nerror) { echo 'error'; exit; } echo 'No errors detected'; ?> then i would unset $pinary and $nerror to spare memory (even though 100% of coders would tell you not to do that). My point, is that you can check it all at once but you could do it differently. I would define an error and simply check if it is true.
  21. my usage of htmlspecialchars is to protect you from someone trying, for example, JavaScript code in place of a name. Atleast htmlspecialchars would prevent the execution of code. You shouldn't use it on a username, email address, password etc. You will instead need to employ some sort of validation, such as regex to check names and numbers. ENT_QUOTES just converts quotations (&quot;). session_destroy: i do not know what you are creating/developing but a login/logout process will be a good idea. However, the session will be lost whenever the user closes the browser unless you are maintaining state with cookies. You could add a logout or destroy session button, which is a post to the test-sesh2.php page. Then in test-sesh2.php, detect a post with your destroy session input and implemement a session_destroy command: if isset $POST 'destroy' then session_destroy(); let us know if you need help implementing session_destroy or validating input...
  22. The first thing I would note about what you have is that it should only have a single condition, because you only have one holiday. If the holiday period is not matched, you will want your default header. These are the types of tasks that you should start to see as better supported with a function. It's also a best practice not to mix your logic with markup. In other words, just have a function that returns one thing, which in your case would be the path to the correct header image. Ideally you should put this type of code into a Function. Here's an example of what you could do: <?php function getSiteHeaderImgFromDate($timeStamp=null) { // Get month and day from today [$m, $d] = explode('-', date('n-j', $timeStamp)); // Check for Christmas Holiday Range if ($m == 12 || ($m == 1 && $d <= 5)) { return 'image/site/site-header-christmas.png'; } else { return 'image/site/site-header.png'; } } Ideally, you would have a small library file of these functions, that you would require_once() at the top of your Scripts. One thing you might notice is that the function requires a $timeStamp parameter. This was done in order to make a function like this testable. If you call the PHP function date() without a timestamp parameter, it will always return the current date, making it impossible to test your condition section. You won't really know if the conditions work without modifying the function source while testing. Another alternative would be to create a unit test for this function that "mocks" the php built-in data() function, but that is a entire subject in itself I'm not going to get into right now. I'll just leave it, that there are libraries you can use like Mockery that can be useful with a problem like this. So for your code, I designed this to be testable by passing a unix timestamp which is what the date() function actually requires. If you don't pass it, it just defaults to the current timestamp. So this allows you to simulate other dates using the php mktime() function. Here are some tests of the function to validate it works. echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 12, 1, 2000)) . PHP_EOL; echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 1, 5, 2000)) . PHP_EOL; echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 1, 6, 2000)) . PHP_EOL; echo getSiteHeaderImgFromDate() . PHP_EOL; The results are: image/site/site-header-christmas.png image/site/site-header-christmas.png image/site/site-header.png image/site/site-header.png So how SHOULD you use this function? Again, Ideally you have the function in a PHP script (along with any other useful functions you might write. One idea would be to call this script something like "site_helpers.php". For this example I'll assume you are doing this in an index.php script.... <?php require_once('site_helpers.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <header> <img class="header__img" src="<?= getSiteHeaderImgFromDate(); ?>"> </header> </body> </html> So hopefully, this illustrates some ideas for you: Using Functions Designing a function to be testable Collecting functions into scripts allowing re-use across different pages. Separating your Markup from PHP code. Using PHP alternative syntax/tags. You should also use it for intermingling control structures in your HTML markup, when that is needed. See https://www.php.net/manual/en/control-structures.alternative-syntax.php
  23. the file system path/filename must be to where the file is located on the disk, either using a relative path (relative to the file with the include/require starting in it) or an absolute path. a leading / refers to the root of the current disk, which is doubtful where that file is located, and which will be producing a php error about a non-existent path/file. you must get php to help you by reporting and displaying all the errors it detects. you can temporarily set php's error_reporting/display_errors in your code (you will want to remove the settings when you are done learning, developing, and debugging). you can add the following immediately after the first opening <?php tag in the main file - ini_set('display_errors', '1'); error_reporting(-1);
  24. a bunch of points - three ... in a relative file system path is invalid. you should be learning, developing, and debugging code on a localhost development system, such xampp. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects? is the main page a .php page? what does the 'view source' of the resulting web page show in the browser? you should use 'require' for things your code must have. your goal is to produce ONE valid web page. the file that you require is not a complete web page, it is only the code/content that you want to be required at that point in the web page. you need to validate the resulting web pages at validator.w3.org all the navigation links you have shown are all the same. you should be dynamically building the web pages using a Content Management System (CMS), in which case the navigation links would be dynamically built too, based on the defined pages, instead of manually creating and managing a bunch of pages yourself.
  25. what does the data look like? is there only one row of data or is there a set of rows of data? modern php no longer assumes that unquoted associative array indexes, that are not defined constants, are strings. you must use quotes around associate array indexes. if you tried the above code, did it produce php errors? do you have php's error_reporting set to E_ALL (it should always be this value) and display_errors set to ON, so that php will help you by reporting and displaying all the errors it detects?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.