简体   繁体   中英

Help with php sessions

I like to know how to use a condition on php sessions

in this code if the user is not loged in page will redirect to login.php.

<?
session_start();
if(!session_is_registered(username)){
header("location: login.php");
}
?> 

what i want is to redirect user to another php if the user is loged in. if not stay on the same page. like if user is not loged in keep the user in index page and if user is loged in redirect the user to user.php

for the login script im using a code fount in this site:http://www.phpeasystep.com/phptu/6.html

thanks in advance.

Set a variable in $_SESSION when you have logged in.

ie in login.php:

if ( $passWordCorrect ) {
 session_start();
 $_SESSION['loggedIn'] = true;
}

in index.php:

session_start();
if ( !empty( $_SESSION['loggedIn'] ) ) {
 // User logged in; do magic.
} else {
 header('Location: user.php');
}
<?
session_start();
if(!$_SESSION['username]){
header("location: login.php");
}
?> 

And in login page you asign the variable like this:

<?php
session_start();
$_SESSION['username']='JohnDoe';
?>

The code is on the same page as the tutorial you linked to:

<?php 
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>

But really you should be using the $_SESSION variable. On the login page:

<?php
session_start()
$_SESSION['username'] = $username;
?>

And then on the other pages:

<?php
session_start()
if (!isset($_SESSION['username'])) {
    header('location: login.php')
}
?>

UPDATE

It is better to not use short tags (ie <?php instead of ?> )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM