PHP Question

Create a php session such that when user is not logged in it will not force them

I want to create a php session such that when user is not logged in, it will not force them to go to the login page but it will show a link to login page.

when we use header() it redirects to the login page. Instead of redirecting I just want to show the login url, the user can stay on the page without logging in but meanwhile session will work if the user is logged in. Just like a shopping website, when you can see the site without logging in.

Please: Answer this question with an example which can also be used.

<?php session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['userSession']))
{ header("Location: index.php"); }
$query = $MySQLi_CON->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array(); $MySQLi_CON->close();
?>


I just don't want to redirect the page. That's all

Answer

You can create a session like this

if (isset($_GET ['session_id'])
   session_id($_GET ['session_id'])

 session_start();

And then suppose the user is not logged in you can use the session id to track the user. Suppose the user adds to cart. you can save it like this

$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'iphone','macbook','ipod'); // Items added to cart

Also if you want to pass the session id in url then you can use

session.use_trans_sid=1

This way you can log the user data using session. You can have a login menu with login URL. No header is required just a menu when clicked directs to login page. Hope I made myself clear.

For your purpose I suggest you change your code

    if(!isset($_SESSION['userSession'])) 
{ header("Location: index.php"); } 
$query = $MySQLi_CON->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']); 
$userRow=$query->fetch_array(); $MySQLi_CON->close(); 

TO

    $value = $user_id;
        if(!isset($_SESSION['userSession'])) 
        { $_SESSION["userSession"]=$value; } 
        if($value != 0){
        $query = $MySQLi_CON->query("SELECT * FROM users WHERE   user_id=".$_SESSION['userSession']); 
        $userRow=$query->fetch_array(); $MySQLi_CON->close(); 
       }

You can set initial $value to 0.