1

What i want i that i can use a variable to use on multiple pages.
The only problem is, is that it doesn't work cause i did something wrong i believe.
After a couple of hours looking at it thinking what could be wrong i decided to post it here, so maybe you can help me.
My code:
login.php:

<?php
    if(empty($_SESSION['pass']))  { 
        echo "U bent niet ingelogt.";
        echo '<form action="index2.php" method="post">';
        echo 'Code <input type="text" name="code">';
        echo '<input type="submit">';
        echo '</form>';
    } else {
        redirect($url);
    }

    $url = "index2.php";
    function redirect($url)
    {
        if (headers_sent()) {
            die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
        } else {
            header('Location: ' . $url);
            die();
        }    
    }
?>

Index2.php:

<?php 
    session_start();
    // error_reporting(0);

    $CODE = $_POST["code"];
    $_SESSION["pass"] = $CODE;
    if ($CODE == "testpassword") {
        echo "password correct";
        echo '<br /><a href="index.php">Index</a>';
    } else {
        echo "Password wrong";
        echo '<br /><a href="login.php">Login</a>';
        exit();
    }
?>

Index.php:

<?php 
    session_start();
    // error_reporting(0);

    $CODE = $_POST["code"];
    $_SESSION["pass"] = $CODE;
    if ($CODE == "testpassword") {
        echo "password correct";
    } else {
        echo "Password wrong";
        exit();
    }
?>
1
  • When i log in, on login.php, and then i get redirected to index2.php(its says password correct). then when i go to index.php it says password wrong while it should be "password correct", since its the same variable. Commented Dec 2, 2013 at 13:11

2 Answers 2

4

You need session_start() on each page that uses $_SESSION[] variables.

Missing in first file.

Sign up to request clarification or add additional context in comments.

8 Comments

I have added session_start(); to the first line, but now (with the same login.php as shown above) all i see is a white screen
You redirect to $url but $url is not set in the else part
Ahh i forgot that, now i will get redirected to index2.php, and its says password correct, but when i got the next page(index.php), it says password wrong.
When you click on the link to "index.php"? Clear..because there is no $_POST['code'] because you submit no formular, so $CODE will be empty in index.php
So how can i make sure i can use the variable in the index.php?
|
2

You forgot session_start(); in login.php.

session_start is used to create or resume existing session. If you don't call it in your script, you can't use $_SESSION array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.