Session will be destroyed on a new pageview

After a successful login, I save the session variable.

When the user navigates to different pages in the application, the session is gone, although I did not explicitly destroy the session. How to fix it?

Here is the page where the session disappears.

<?php include 'core/init.php'; include 'core/sendmessage.php'; $user_info = $_SESSION['user_id']; $getUser = mysql_query("SELECT * FROM users WHERE user_id = ".$uid); $user_info = array(); while($currentRow = mysql_fetch_array($getUser)){ $user_info['firstname'] = $currentRow['first_name']; $user_info['lastname'] = $currentRow['last_name']; $user_info['username'] = $currentRow['username']; } ?> 

Inside core/init.php I have a method to start a session.

 <?php session_start(); require 'database/connect.php'; require 'functions/users.php'; require 'functions/general.php'; if (logged_in() === true) { $user_data = user_data($_SESSION['user_id'],'first_name','last_name','username'); } $errors = array(); ?> 
+4
source share
2 answers

session_start () creates a session or resumes the current one based on the session identifier passed through a GET or POST request, or passed through a cookie. (Visit PHP: session_start )

Add session_start() to the top of each page (after the <?php tag).

In your case:

 <?php if(!isset($_SESSION)) session_start(); //--> ADD this line include 'core/init.php'; include 'core/sendmessage.php'; $user_info = $_SESSION['user_id']; ... 
+2
source

You should try using a different name for all this, since I don’t think it’s good practice to use the value that you use for the session for a different value (as this will replace your old value) and make the session disappear the next time you visit this page. A session is created only once.

 <?php include 'core/init.php'; include 'core/sendmessage.php'; $user_info = $_SESSION['user_id']; $getUser = mysql_query("SELECT * FROM users WHERE user_id = ".$uid); $userinfo = array(); //I changed $user_info to $userinfo so it doesn't get mixed with the session. while($currentRow = mysql_fetch_array($getUser)){ //I removed the underscore $userinfo['firstname'] = $currentRow['first_name']; $userinfo['lastname'] = $currentRow['last_name']; $userinfo['username'] = $currentRow['username']; } ?> 

This should be fine now, although I have not tested it. I just changed the array to $userinfo so that you can still use the session at all times without mixing it with something.

0
source

Source: https://habr.com/ru/post/1442192/


All Articles