开发者

Session Redirects

I am trying to protect a page by making it password protected. I am using the code below, but it doesn't work.

home.php

                session_start(); 



         // Process the POST variables
           $username = $_SESSION["user_name"];
              //$password = $_POST["password"];


            // Set up the session variables
            $_SESSION["user_name"] = $username开发者_JAVA百科;

              if(!isset($_SESSION['user_name'])) { header('Location: login.php'); die('<a  href="login.php">Login first!</a>'); }

Relevant portion of login.php

           <?php

            session_start(); 



             // Process the POST variables
          $username = $_SESSION["user_name"];
           //$password = $_POST["password"];


                // Set up the session variables
              $_SESSION["user_name"] = $username;


Try this

session_start(); 

if(!isset($_SESSION['user_name'])) 
{ 
   header('Location: login.php'); 
   exit;
}

$username = $_SESSION["user_name"];
$password = $_SESSION["password"]; *//EDITED*

EDIT:

On login.php

<?php
    session_start(); 

    if(isset($_SESSION['user_name'])) 
    { 
        header('Location: home.php'); 
        exit;
    }
?>

<input type = 'text' name = 'login' />
<input type = 'password' name = 'password' />
<input type = 'submit' name = 'submit' />

EDIT 2:

After your successful login write this

$_SESSION["user_name"] = $_POST["user_name"];
$_SESSION["password"] = $_POST["password"];

This will set post in session variable So it will look like this Now when you check if(isset($_SESSION['user_name'])) it will return true and redirect to home page


Just a guess since you haven't really asked the question fully. But try replacing:

$username = $_SESSION["user_name"];

with

$username = $_POST["user_name"];


In both your login.php and home.php you are using:

// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];

// Set up the session variables
$_SESSION["user_name"] = $username;

That does not make sense at all, you only set your session variable when your login criteria is met (successfull login) and nowhere else. In other places you just check if it exists / is set.

As you have not posted the part where the login is processed, it´s hard to say if there are any other errors.


It seems that you are copying over an empty username, and then changing the value of an empty $username to your session's array.

You want to modify your session's information as little as possible.

so in your update page:

<?php

session_start();

// is the line below necessary on this page?
if ( $_POST['user_name'] != "" ) {
    $_SESSION['user_name'] = $_POST['user_name'];
}

if ( ( trim($_SESSION['user_name']) != "" ) ) {
     echo $_SESSION['user_name'];
} else {
     header("Location: login.php");
     die();
}

Updated: removed the comment line

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜