Jump to content

Login Script $_Session and Cookies


Wemperer

Recommended Posts

I'm trying to create a login script but I can't figure out how to pull the data out of a $_COOKIE and how cookies work with $_SESSION.

 

Basically I have this

	
	
//pull data from database	
	$myusername=$_POST['myusername'];
	$mypassword=$_POST['mypassword'];

//store in the database strip for sql injection
	$myusername = stripslashes($myusername);
	$mypassword = stripslashes($mypassword);
	$myusername = mysql_real_escape_string($myusername);
	$mypassword = mysql_real_escape_string($mypassword);
	

//query database, check to see if username and password exist there / encrypt
	$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password=SHA('$mypassword')";
	$result=mysql_query($sql);

	$count=mysql_num_rows($result);

//if it exists, register the session with the username nad password, then set a cookie
	if($count==1)
	{


	$_SESSION("myusername");
	$_SESSION("mypassword");
	setcookie("username","$myusername",0);
	header("location:cookietest.php");
	}
	else 
		{
			echo "Wrong Username or Password";
		}
		

Then inside my cookietest.php..

	if(isset($_SESSION['username']))
			echo "session varible set and ";
		else
			echo "session varibale not set and ";
			
	if(isset($_COOKIE['username']))
		echo "cookie is set";
	else
		echo "cookie is not set";

Even thogh I can see int he browser that the cookie was created I get "session varible not set and cookie is not set"

Link to comment
https://forums.phpfreaks.com/topic/280940-login-script-_session-and-cookies/
Share on other sites

A couple of things. You need to do session_start(); at the top of your program. Then, set session variables as

$_SESSION['myvar']=$myvar ;

Don't store the password in a session variable, just the fact that the user successfully logged in.

Ok I was under the impression that SESSION relied on COOKIES. Apparently they CAN work together but session is sufficient enough.

Yes, you do not need to store anything in cookies unless you want a user's login to last after they have closed their browser.

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.