Nave Tseva
Nave Tseva

Reputation: 878

Check if session doesn't exist php

I have the following php code :

<?php 
if (!(session_id('password')) || !(session_id('user_name'))) {    
    header("Location: ../../"); /* Redirect browser */
}
 ?>

Which should check if session doesn't exist, and if it doesn't, the user redirects, the problem is that this condition is always true, even when the session does exists, my question is how can I fix it?

Upvotes: 2

Views: 17409

Answers (3)

GautamD31
GautamD31

Reputation: 28763

Try with $_SESSION like

<?php 
   if (!isset($_SESSION) || !isset($_SESSION['password']) || !isset($_SESSION['user_name'])) {
         header("Location: ../../"); /* Redirect browser */
   }
?>

Upvotes: 7

Rahul
Rahul

Reputation: 1181

  1. check if you have started session on that page or not ?

use session_start(); at the top of page..

  1. with your if condition just add:

if( isset($_session) && ...);

  1. session_id() is used to generate a session id not to check session variable.

so use $_SESSION['username'] && $_SESSION['password']

  1. passing password in session is highly discourages.

Upvotes: 0

verv
verv

Reputation: 686

session_id() is not used to fetch session information. It is used to change the user's session ID. What you have done is changed everyone's session ID to the string "user_name".

Instead do this;

if( empty( $_SESSION[ 'user_name' ] ) ) header("Location: ../../");

I wouldn't recommend storing the user's password in the session. There is no reason to and it's just safer to leave it out.

Upvotes: 6

Related Questions