Jump to content

Session Not Starting


Mzor

Recommended Posts

I am fairly new to PHP, and thus it may be something really stupid I'm missing here, but please bear with me.

 

I have a log in form for my site which starts a session for the user, but for some reason I often have to log in twice for the session to take effect. So I know it works, it just doesn't work the first time.

 

Here is my code: (There is a form later on but I don't think that is part of th problem)

 

 


<?php

//Check for submitted form
if(isset($_POST['submitted'])) {

  //Connect to mysql database
  require_once ('./mysql_connect.php');
  
  //Set errors array
  $errors = array();
  
  if(empty($_POST['username'])) {
  
    $errors[] = 'You forgot to enter your username.';
  
  } else {
  
    $un = $_POST['username'];
  
  }

  if(empty( $_POST['password'] )) {
  
    $errors[] = 'You forgot to enter your password.';
  
  } else {
  
    $p = $_POST['password'];
  
  }

  //If form was submitted properly
  if(empty($errors)) {
  
    //Make query and put results into array
    $query = "SELECT user_id, username FROM users WHERE username='$un' AND password=SHA('$p')";
    $result = @mysql_query ($query);
    $row = mysql_fetch_array ($result, MYSQL_NUM);
    
    if($row) {
    
      //Start session
      session_start();
      $_SESSION['user_id'] = $row[0];
      $_SESSION['username'] = $row[1];
      
      //Redirect
      $url = 'http://www.sitename.com';
      header("Location: $url");
      exit();
       
    } else {
    
      $errors[] = 'The username and password entered do not match.';
      $errors[] = mysql_error() . '<br /><br />Query: ' . $query;
    
    }
  
  }
  mysql_close();

} else {

  $errors = NULL;

}


?>

 

Any ideas? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/142280-session-not-starting/
Share on other sites

Maybe on your first pass if($row) is not set, so it doesn't set the session.  Try adding a echo in there after you set the session and check.

 

Also, turn on display errors and error reporting to see if you are getting a error saying headers already sent, if so, move your session_start() up to the top of your code.

Link to comment
https://forums.phpfreaks.com/topic/142280-session-not-starting/#findComment-745430
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.