Jump to content

[SOLVED] slight problem with Session Start after login


webguync

Recommended Posts

Hi,

 

I have a login for where the user enters username and password and is redirected if login is successfull to another page. At the top of the page I start a session with the following code

 

<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}

 

problem is the redirect back to the login screen occurs if the username is being set or not, so it's an infinite redirect! Not sure why?

Link to comment
Share on other sites

when I place it further down the page, I get a "header already sent error"

 

the code I am using is this

 


<?php
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);
$con = mysql_connect("localhost","uname","pw");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("DB", $con);




// Same checking stuff all over again.
if(isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['pwid']) ) {
	echo "Sorry, you have to fill in both your name, username and password";
                exit;
}
// Create the variables again.

$username = $_POST['username'];
$pwid = $_POST['pwid'];
// Encrypt the password again with the md5 hash. 
// This way the password is now the same as the password inside the database.
$pwid = md5($pwid);

// Store the SQL query inside a variable. 
// ONLY the username you have filled in is retrieved from the database.
$query = "SELECT username,pwid
		  FROM	roster
		  WHERE	 username='$username'";

$result = mysql_query($query);
if(!$result) { 
	// Gives an error if the username given does not exist.
	// or if something else is wrong.
	echo "The query failed " . mysql_error();
} else {
	// Now create an object from the data you've retrieved.
	$row = mysql_fetch_object($result);
	// You've now created an object containing the data.
	// You can call data by using -> after $row.
	// For example now the password is checked if they're equal.
	//if($row->pwid != $pwid) {
		//echo "I am sorry, but the passwords are not equal.";
                      //  exit;
	//}
	// By storing data inside the $_SESSION superglobal,
	// you stay logged in until you close your browser.
	$_SESSION['username'] = $username;
	$_SESSION['sid'] = session_id(); 
	// Make it more secure by storing the user's IP address.
	$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
	// Now give the success message.
	// $_SESSION['username'] should print out your username.

echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";
//echo "<a href="logout.php">Logout</a>";


}
}

// Start a session. If not logged in will be redirected back to login screen.
session_start();
if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}

?>

Link to comment
Share on other sites

upon looking at your code a little bit, do you not intend to check both the username AND password when somebody logs in?  right now you're just checking the username, and you haven't even done anything to verify it's integrity.

 

sorry, off topic .. just curious.

Link to comment
Share on other sites

you must have session_start(); at the top of the page, before working with any $_SESSION vars .. so this...

// Start a session. If not logged in will be redirected back to login screen.
session_start();
if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}

being at the bottom of the page is a problem.

 

this should be :

$_SESSION['username'] = $row['username'];

because you only want the username value that's in the db, not whatever the user sets the $_POST['username'] value as.  think security.

Link to comment
Share on other sites

session start must be the first line in your code (it has to come beofre you can do anything with sessions so it common to put this line in first to avoid any confusion).

 

you don't appear to be checking the password and that code is open to sql injection attacks.

 

headers already sent is because you have outputted some html before you you try the redirect.  you cannot start output (even whitespace) before sending headers unless you use output buffering...

 

 

 

Link to comment
Share on other sites

ok, so I need to add session start();

at the top of the page

 

and then

 

$_SESSION['username'] = $row['username'];

 

How would I do the redirect?

 

header("Location:ExamLogin.php");

 

also how would I check the password and prevent SQL injection?

 

do I just need to change the SQL Query

 

$query = "SELECT username,pwid

  FROM centacor_roster

  WHERE username='$username' AND pwid='pwid'";

 

 

Link to comment
Share on other sites

create a function like so :

function cleanPost($input) {
     if (get_magic_quotes_gpc()) {
            $input= stripslashes($input);
     }
     $output = mysql_real_escape_string($input);

     return $output;
}

then, do your query...

$query = mysql_query(sprintf("SELECT username, pwid FROM centacor_roster WHERE username='%s' AND pwid=md5('%s') LIMIT 1", cleanPost($_POST['username']), cleanPost($_POST['pwid'])));

if (mysql_num_rows($query) > 0) {
     //declare your variables, etc...
} else {
     //get outta dodge;
}

and ya, your header() redirect is fine.

 

Link to comment
Share on other sites

<?php
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);

session_start();

$con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error());

mysql_select_db("DB", $con);




// Same checking stuff all over again.
if(isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['pwid']) ) {
	echo "Sorry, you have to fill in both your name, username and password";
                exit;
}
// Create the variables again.

$username = mysql_real_escape_string($_POST['username']);
$pwid = $_POST['pwid'];
// Encrypt the password again with the md5 hash. 
// This way the password is now the same as the password inside the database.
$pwid = md5($pwid);

// Store the SQL query inside a variable. 
// ONLY the username you have filled in is retrieved from the database.
$query = "SELECT username,pwid
		  FROM	roster
		  WHERE
		  password = '$pwid'
		  AND
		  username='$username'";

$result = mysql_query($query);
if(!$result) { 
	// Gives an error if the username given does not exist.
	// or if something else is wrong.
	echo "The query failed " . mysql_error();
exit();
/*
this would benefit from a redirect to a page giving better information to
the user and maybe logging some errors.
*/
} else {
	// Now create an object from the data you've retrieved.
	$row = mysql_fetch_object($result);
	// You've now created an object containing the data.
	// You can call data by using -> after $row.
	// For example now the password is checked if they're equal.

	// By storing data inside the $_SESSION superglobal,
	// you stay logged in until you close your browser.
	$_SESSION['username'] = $username;
	$_SESSION['sid'] = session_id(); 
	// Make it more secure by storing the user's IP address.
	$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
	// Now give the success message.
	// $_SESSION['username'] should print out your username.

//move this to after your redirect further below..

}
}

// Start a session. If not logged in will be redirected back to login screen.

if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}
echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";

echo "<a href="logout.php">Logout</a>";

?>

 

Link to comment
Share on other sites

for some reason, when I try and go to the display page without logging in, instead of being directed back to the login page, the page displays, but I also get this notice.

 

Notice: Undefined variable: username in /var/www/vhosts/etsi-dataservices.com/httpdocs/Centocor/April09/index_test.php on line 92

 

why isn't the redirect working?

 

here is the updated code

 

[php
<?php
session_start();
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);
$con = mysql_connect("localhost","username","pw");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("DBName", $con);




// Same checking stuff all over again.
if(isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['pwid']) ) {
echo "Sorry, you have to fill in both your name, username and password";
                exit;
}
// Create the variables again.

$username = mysql_real_escape_string($_POST['username']);
$pwid = $_POST['pwid'];
// Encrypt the password again with the md5 hash.
// This way the password is now the same as the password inside the database.
$pwid = md5($pwid);

// Store the SQL query inside a variable.
// ONLY the username you have filled in is retrieved from the database.
$query = "SELECT username,pwid
          FROM  roster
          WHERE
          pwid = '$pwid'
          AND
          username='$username'";

$result = mysql_query($query);
if(!$result) {
// Gives an error if the username given does not exist.
// or if something else is wrong.
echo "The query failed " . mysql_error();
} else {
// Now create an object from the data you've retrieved.
$row = mysql_fetch_object($result);
// You've now created an object containing the data.
// You can call data by using -> after $row.
// For example now the password is checked if they're equal.
//if($row->pwid != $pwid) {
//echo "I am sorry, but the passwords are not equal.";
                      //  exit;
//}
// By storing data inside the $_SESSION superglobal,
// you stay logged in until you close your browser.
$_SESSION['username'] = $username;
$_SESSION['sid'] = session_id();
// Make it more secure by storing the user's IP address.
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
// Now give the success message.
// $_SESSION['username'] should print out your username.

echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";
echo "<a href='logout.php'>Logout</a>";


}
}

// Start a session. If not logged in will be redirected back to login screen.

if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}
echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";

echo "<a href='logout.php'>Logout</a>";

?>
[/code]

Link to comment
Share on other sites

sorry code didn't post correctly before

 

<?php
session_start();
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);
$con = mysql_connect("localhost","uname","pw");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("DB", $con);




// Same checking stuff all over again.
if(isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['pwid']) ) {
	echo "<h3>Sorry, you have not filled in the information, as we have it in our database. Please try again. If you continue to have difficulty, please contact your administrator.</h3>";
                exit;
}
// Create the variables again.

$username = mysql_real_escape_string(stripslashes($_POST['username']));
    $pwid = mysql_real_escape_string(stripslashes($_POST['pwid']));
// Encrypt the password again with the md5 hash. 
// This way the password is now the same as the password inside the database.
$pwid = md5($pwid);

// Store the SQL query inside a variable. 
// ONLY the username you have filled in is retrieved from the database.
$query = "SELECT username,pwid
           FROM   roster
           WHERE
           pwid = '$pwid'
           AND
           username='$username'";

$result = mysql_query($query);
if(!$result) { 
	// Gives an error if the username and password given does not exist.
	// or if something else is wrong.
	echo "The query failed " . mysql_error();
} else {
	// Now create an object from the data you've retrieved.
	$row = mysql_fetch_object($result);
	// You've now created an object containing the data.
	// You can call data by using -> after $row.
	// For example now the password is checked if they're equal.
	//if($row->pwid != $pwid) {
		//echo "I am sorry, but the passwords are not equal.";
                      //  exit;
	//}
	// By storing data inside the $_SESSION superglobal,
	// you stay logged in until you close your browser.
	$_SESSION['username'] = $username;
	$_SESSION['sid'] = session_id(); 
	// Make it more secure by storing the user's IP address.
	$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
	// Now give the success message.
	// $_SESSION['username'] should print out your username.



}
}

// Start a session. If not logged in will be redirected back to login screen.

if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}

echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";

echo "<a href='logout.php'>Logout</a>";


?>

 

 

issue are redirect still isn't working when navigating to page where you should be sent only if logged in and it doesn't look like the PWID check is working, b/c you can put in any password and login.

Link to comment
Share on other sites

Quick example for you, i hope it helps.

 

Not cheeked, as i written it here and now, don't no if there errors.

 

<?php session_start();


$database_connection("localhost","username","password") or die("dataabse connection problam".mysql_error());

$database_result=mysql_select_db("database_name",$database_connection);


if(!isset($_SESSION['username'])){

$warning[]="<h1>You are not allowed to see <br> or use this page, unless a member or logged in!</h1>";

header("refresh: 5; url=login.php");

exit;
}


if(isset($_POST['submit'])){


$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string(md5($_POST['password']));

if((empty($username))|| empty($password)){

	$warning[]="Please use all the form.";

}else{

	$sql="SELECT username, password FROM users_info WHERE username='$username' AND password='$password'";

	$sql_result=mysql_query($sql)or die("Select problam error".mysql_error());

	if(mysql_num_rows($sql_result)==1){

		while($data=mysql_fetch_assoc($sql_result)){

			$_SESSION['username']=$data['username'];

			if(isset($_SESSION['username'])){

				echo "<center>Hello member {$_SESSION['username']}\n your loged in.";

				exit;
			}

		}

	}else{

		$warning[]="<h1>You are not allowed to see <br> or use this page, unless a member or logged in!</h1>";

		header("refresh: 5; url=login.php");

		exit;
	}
}


if(isset($warning)){

	foreach($warning as $warn)

	echo $warn;
}

}
?>

Link to comment
Share on other sites

I try this, but receive a blank white page. Not sure why the error isn't being reported. Hoping someone with good PHP debugging program can help.

 

<?php session_start();
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);

$database_connection= mysql_connect("localhost","username","pw") or die("could not connect to database".mysql_error());

$database_result=mysql_select_db("DBName",$database_connection);


if(!isset($_SESSION['username'])){

   $warning[]="<h1>You are not allowed to see <br> or use this page, unless a member or logged in!</h1>";

   header("refresh: 5; url=ExamLogin_Test.php");

   exit;
}


if(isset($_POST['submit'])){


   $username=mysql_real_escape_string($_POST['username']);
   $password=mysql_real_escape_string(md5($_POST['pwid']));

   if((empty($username))|| empty($password)){

      $warning[]="Please enter your username and WWID.";

   }else{

      $sql="SELECT username, pwid FROM roster WHERE username='$username' AND pwid='$password'";

      $sql_result=mysql_query($sql)or die("Error selecting data".mysql_error());

      if(mysql_num_rows($sql_result)==1){

         while($data=mysql_fetch_assoc($sql_result)){

            $_SESSION['username']=$data['username'];

            if(isset($_SESSION['username'])){

              echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";

echo "<a href='logout.php'>Logout</a>";

               exit;
            }

         }

      }else{

         $warning[]="<h1>You are being directed to our login page!</h1>";

         header("refresh: 5; url=ExamLogin_Test.php");

         exit;
      }
   }


   if(isset($warning)){

      foreach($warning as $warn)

      echo $warn;
   }

}

?>

Link to comment
Share on other sites

Jesus H...

 

have a look at your very first conditional!!! we've touched on this about 5 times in this thread alone...

 

how do you expect your code to check the users against database records when you have that code before the verification...

Link to comment
Share on other sites

well, I wasn't getting an error, just a blank page.

 

I am back to this code which doesn't produce an error, but it isn't checking correctly for the password (pwid), b/c you can add anything for the password and it will get you through.

 

<?php
ini_set("display_errors","1");
ERROR_REPORTING(E_ALL);

session_start();

$con = mysql_connect("localhost","un","pw") or die('Could not connect: ' . mysql_error());

mysql_select_db("db", $con);




// Same checking stuff all over again.
if(isset($_POST['submit'])) {
   if(empty($_POST['username']) || empty($_POST['pwid']) ) {
      echo "Sorry, you have to fill in both your name, username and password";
                exit;
   }
   // Create the variables again.
   
   $username = mysql_real_escape_string($_POST['username']);
   $pwid = $_POST['pwid'];
   // Encrypt the password again with the md5 hash. 
   // This way the password is now the same as the password inside the database.
   //$pwid = md5($pwid);

   // Store the SQL query inside a variable. 
   // ONLY the username you have filled in is retrieved from the database.
   $query = "SELECT username,pwid
           FROM   my_roster
           WHERE
           pwid = '$pwid'
           AND
           username='$username'";

   $result = mysql_query($query);
   if(!$result) { 
      // Gives an error if the username given does not exist.
      // or if something else is wrong.
      echo "The query failed " . mysql_error();
exit();
/*
this would benefit from a redirect to a page giving better information to
the user and maybe logging some errors.
*/
   } else {
      // Now create an object from the data you've retrieved.
      $row = mysql_fetch_object($result);
      // You've now created an object containing the data.
      // You can call data by using -> after $row.
      // For example now the password is checked if they're equal.

      // By storing data inside the $_SESSION superglobal,
      // you stay logged in until you close your browser.
      $_SESSION['username'] = $username;
      $_SESSION['sid'] = session_id(); 
      // Make it more secure by storing the user's IP address.
      $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
      // Now give the success message.
      // $_SESSION['username'] should print out your username.

//move this to after your redirect further below..
      
   }
}

// Start a session. If not logged in will be redirected back to login screen.

if(!isset($_SESSION['username'])){
header("Location:ExamLogin.php");
exit;
}
echo "<h3>Welcome! You are now logged in " . $_SESSION['username'] . "</h3>";

echo "<a href='logout.php'>Logout</a>";

?>

Link to comment
Share on other sites

Ok try this:

Change mysql_select_db("db", $con); to mysql_select_db("db") or die(mysql_error());

Change mysql_query($query); to mysql_query($query) or die(mysql_error());

Change if(!$result) to if(mysql_num_rows($result) == 0)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.