Mzor Posted January 24, 2009 Share Posted January 24, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/142280-session-not-starting/ Share on other sites More sharing options...
revraz Posted January 24, 2009 Share Posted January 24, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/142280-session-not-starting/#findComment-745430 Share on other sites More sharing options...
DeanWhitehouse Posted January 24, 2009 Share Posted January 24, 2009 Also remove the @ from the sql query, and add or die(mysql_error()) to it. Example $sql = mysql_query($query) or die(mysql_error()); Quote Link to comment https://forums.phpfreaks.com/topic/142280-session-not-starting/#findComment-745433 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.