Setting php sessions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tdrsam
    New Member
    • May 2015
    • 97

    Setting php sessions

    I'm trying to register new users and store their email address and password to a db, which is working fine, but I'm also trying to set a session, so that the page they land on after they register is a protected page.

    I'm using a standard form which runs this when the form is submitted:

    Code:
    <?php
    // connect to db manager
    $link = mysql_connect("localhost", "root", "");
    if (!$link) {die('Database Error: Could not connect: ' . mysql_error());}
    
    // select db
    $db_selected = mysql_select_db('foo', $link);
    if (!$db_selected) {
        die ('Can\'t use foo : ' . mysql_error());
    }
    
    // username and password sent from form
    $em = mysql_real_escape_string($_POST['email']);
    $pw = mysql_real_escape_string($_POST['password']);
    
    // MySQL Insert Statement
    $insert = "INSERT INTO users (`email`, `password`) VALUES ('$em',AES_ENCRYPT('$pw','secretKey'))";
    
    // Perform Query
    $execute = mysql_query($insert);
    
    // Check result
    // Show Error Message If Not Inserted
    if (!$execute) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        die($message);
    }
    // Set Session + Redirect If New User Inserted
    elseif(session_id())
    {
         // session has been started
         echo '<script type="text/javascript">';
         echo 'document.location.href = "../u/user.php";';
         echo '</script>';
    }
    else
    {
         // session has NOT been started
         session_start();
         echo '<script type="text/javascript">';
         echo 'document.location.href = "../u/user.php";';
         echo '</script>';
    }
    
    mysql_close($link);
    ?>
    And at the top of the document for the page `u/user.php` which is where the user is supposed to be redirected to after they register, there's this:

    Code:
    <?php
    session_start();
    if (empty($_SESSION[''])){
    header("location:../index.php");
    }
    ?>
    But this redirects me to the `../index.php` page every time I run a test to insert a new user to the db, which means that the session either must be empty or there's a session variable that's missing.

    Where am I going wrong? I've only done this once or twice before and not for a while, and I can't remember how this works. I also can't really find information about it. I'm sure it's out there, I just can't find it. I must be googling the wrong phrases.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    you never set $_SESSION[''], so it's always empty.

    Comment

    Working...