singingsands Posted February 23 Share Posted February 23 This should be simple but it isn't working and I'm so frustrated I could spit. I'm simply trying to pass 2 session variables from one page to another. I should mention this is not for a login. Following is a pared down version of my code. When I enter name and number and submit nothing happens. Any help would do wonders for my sanity. test-sesh.php <?php session_start(); if (isset($_SESSION['name'])) { header("Location: test-sesh-2.php"); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['submit'])) { $name = $_POST['name']; $number = $_POST['number']; } } ?> <!DOCTYPE html> <html> <head> <title>Test $_SESSION</title> </head> <body> <h1>Test $_SESSION</h1> <form method="post"> <label for="name">Name:</label> <input type="text" name="name" required><br> <label for="number">Number:</label> <input type="text" name="number" required><br> <button type="submit" name="register">Submit</button> </form> </body> </html> test-sesh-2.php <?php session_start(); if (!isset($_SESSION['number'])) { header("Location: test-sesh.php"); exit; } $name = $_SESSION['name']; $number = $_SESSION['number']; ?> <!DOCTYPE html> <html> <head> <title>User Dashboard</title> </head> <body> <h1><?php echo $name." ".$number?></h1> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/326852-problem-with-_session-variables/ Share on other sites More sharing options...
Solution jodunno Posted February 23 Solution Share Posted February 23 48 minutes ago, singingsands said: I should mention this is not for a login. but it looks and functions like a login. You even refer to the poster as User in test-sesh2.php I feel compelled to mention that it is, in fact, a login of sorts. Anyway, i'm sure that this post will attract alot of helpful posts because your code is insecure among other things. I will just point out what makes it function and leave the rest to other members. 52 minutes ago, singingsands said: if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['submit'])) { $name = $_POST['name']; $number = $_POST['number']; } } here you are assigning the post values to php variables ($name and $number) instead of session variables AND you are checking if 'submit' is set but your input type submit name is actually 'register'. If you cannot remember 'register', then change it to 'submit' to avoid further complication. Thus, if you correct these errors, then your session test should work. But you shouldn't be assigning input to variables of any type without validating and filtering. Furthermore, if a User should be remembered longterm, then switch to a database for storing names and numbers and leave the session out of it. test-sesh.php <?php session_start(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['register'])) { if (!empty($_POST['name']) && !empty($_POST['number'])) { $_SESSION['name'] = htmlspecialchars($_POST['name'], ENT_QUOTES); $_SESSION['number'] = htmlspecialchars($_POST['number'], ENT_QUOTES); } } } if (isset($_SESSION['name'])) { header("Location: test-sesh-2.php"); exit; } ?> <!DOCTYPE html> <html> <head> <title>Test $_SESSION</title> </head> <body> <h1>Test $_SESSION</h1> <form method="post"> <label for="name">Name:</label> <input type="text" name="name" required><br> <label for="number">Number:</label> <input type="text" name="number" required><br> <button type="submit" name="register">Submit</button> </form> </body> </html> test-sesh2.php <?php session_start(); if (!isset($_SESSION['number'])) { header("Location: test-sesh.php"); exit; } ?> <!DOCTYPE html> <html> <head> <title>User Dashboard</title> </head> <body> <h1><?php echo $_SESSION['name']." ".$_SESSION['number']; ?></h1> </body> </html> I hope that this helps, John Quote Link to comment https://forums.phpfreaks.com/topic/326852-problem-with-_session-variables/#findComment-1650334 Share on other sites More sharing options...
singingsands Posted February 23 Author Share Posted February 23 Quote it looks and functions like a login. I adapted it from a login script. When I searched for examples of how to use the session variable all that came up was login scripts. Is there another way to do it? The name "register" was a leftover from the original that I missed. The user variable will be something else. Thanks so much, this does the trick. What is the purpose of ENT_QUOTES? I haven't seen that anywhere else. One more question: where is the best place to put session_destroy? Quote Link to comment https://forums.phpfreaks.com/topic/326852-problem-with-_session-variables/#findComment-1650335 Share on other sites More sharing options...
jodunno Posted February 23 Share Posted February 23 (edited) 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 ("). 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... Edited February 23 by jodunno changed test-sesh to test-sesh2 Quote Link to comment https://forums.phpfreaks.com/topic/326852-problem-with-_session-variables/#findComment-1650339 Share on other sites More sharing options...
Strider64 Posted February 24 Share Posted February 24 I use a `session token` in a configuration file: <?php // Set error reporting level error_reporting(E_ALL); // Disable display of errors ini_set('display_errors', '0'); // Enable error logging ini_set('log_errors', '1'); // Set the path for the error log file ini_set('error_log', __DIR__ . '/error_log/error_log_file.log'); 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) { } } ini_set('memory_limit', '512M'); // Increase to 512MB that way when someone logins in -> // 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 based on security level $securityLevel = $_SESSION['security_level']; if (in_array($securityLevel, ['admin','member','moderator', 'sysop'], true)) { header('Location: member.php'); } else { // Fallback for unexpected security levels header('Location: index.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)); and here's my verification of the login credentials: public function verify_credentials($username, $password): bool { $sql = "SELECT id, password, security FROM {$this->table} WHERE username = :username LIMIT 1"; $stmt = $this->pdo->prepare($sql); $stmt->execute(['username' => $username]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user && password_verify($password, $user['password'])) { session_regenerate_id(true); // Prevent session fixation attacks $_SESSION['user_id'] = $user['id']; $_SESSION['security_level'] = $user['security']; // Store user's role return true; } return false; } The only thing I put in session is the user's id and `security level` , plus logging out relatively easy: logout.php <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/starlite_config.php'; require_once "vendor/autoload.php"; // Import the ErrorHandler and Database classes from the PhotoTech namespace. use clearwebconcepts\{ ErrorHandler, Database, LoginRepository as Login }; $errorHandler = new ErrorHandler(); $database = new Database(); $pdo = $database->createPDO(); $loginRepository = new Login($pdo); $loginRepository->logoff(); and the method (function): public function logoff(): void { if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 3600, '/'); } if (isset($_SESSION['user_id'])) { $sql = "UPDATE {$this->table} SET token = NULL WHERE id = :id"; $stmt = $this->pdo->prepare($sql); $stmt->execute(['id' => $_SESSION['user_id']]); } $_SESSION = []; session_destroy(); header('Location: index.php'); exit(); } This might give you some ideas or help a little? 🤷♂️ Quote Link to comment https://forums.phpfreaks.com/topic/326852-problem-with-_session-variables/#findComment-1650402 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.