Jump to content

setting cookies


Faracus

Recommended Posts

I am trying to get the page to set a cookie once verifying that the person is actually a registered user, but when I test the script I am getting a "unexpected T_ELSE" error. Anyone able to help. I have included the portion of code in question.

<?php $con = mysql_connect("localhost","user","password");if (!$con)  {  die('Could not connect: ' . mysql_error());  }    mysql_select_db("shackguys", $con);$query = "SELECT * FROM accounts WHERE uname = '" . mysql_real_escape_string($_POST['uname']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'";// Perform Query$result = mysql_query($query);// Check result// This shows the actual query sent to MySQL, and the error. Useful for debugging.if (!$result) {$message = 'Invalid query: ' . mysql_error() . "\n";$message .= 'Whole query: ' . $query;die($message);}if ($result['uname'] == "$_POST[uname]")setrawcookie("user", $_POST['uname'], time()+1800);echo "Congratulations $_COOKIE[user] you have logged in.<br>  <a href='./console.php'>Click Here</a> to continue.";else  echo "Username not found or password incorrent";?>

Link to comment
Share on other sites

Since you're writing more than one instruction after the if statement I recommend putting it between brackets { }.I'm not sure if this is the reason it's not working but it looks probable.

if ($result['uname'] == "$_POST[uname]") {setrawcookie("user", $_POST['uname'], time()+1800);echo "Congratulations $_COOKIE[user] you have logged in.<br>  <a href='./console.php'>Click Here</a> to continue.";} else {echo "Username not found or password incorrent";}?>

Link to comment
Share on other sites

yes that is it, but when submitting my data, then i get the error that the username is not found or pass is incorrect. so is the if () satement correct to make sure that whats in the data base matches what the user has entered?

Link to comment
Share on other sites

It looks funny, having the different style of quote marks, but both styles are valid, so yeah. Here are some ideas.Echo both values like this:echo "START {$result['uname']} {$_POST['uname']} END";If you see a difference right off, then you'll know.If not, view the source. All four values should be on one line. You might have a newline in there. A simple linebreak anywhere would show it. If not, then get a strlen for both values and echo those. A difference might suggest some other non-printing character has gotten into the mix.Either of those problems can be solved with a call to trim(). Of course the bigger wonder (if there is one) would be where the extra character comes from.

Link to comment
Share on other sites

ok, I took your adivce, but insted I added a , between the two so I knew which one was working and what wasn't and $result['uname'] is just returning a blank.

Link to comment
Share on other sites

Go ahead and print_r($result), but I bet the whole thing is empty. $result tests true because it has keys, not necessarily values. If that's the case, better post the problem in SQL.

Link to comment
Share on other sites

If I understand you correctly you want to set cookie for registering users and they do not need to log in again if they allowed a cookies . Or your cookie is using to remember the login of the user . Can you explain, what is your cookie for ?Sorry if I miss understand you .

Link to comment
Share on other sites

the user "should" already have a account registered and this is setting a cookie for them to remain signed in throughout the website.also print_r returns "Resource id #3"

Link to comment
Share on other sites

->Faracusso is the if () satement correct to make sure that whats in the data base matches what the user has entered?This is the way how did I search my Database for Firstname or username

$con = mysql_connect("localhost","root","");mysql_select_db("my_db", $con);$result = mysql_query("SELECT * FROM person");while($row = mysql_fetch_array($result)) //this command will loop until reach the end of database {	if ( $_POST[firstname]==$row['FirstName'] ) //this just check is there Fristname in database	{	// then you post your depend here 		 }}

Hope this helps .

Link to comment
Share on other sites

ok I tryed that method, and it works, well kinda.this is what came up:Username not found or password incorrentBackUsername not found or password incorrentBackCongratulations you have logged in.Click Here to continue.Username not found or password incorrentBackUsername not found or password incorrentBackUsername not found or password incorrentBackUsername not found or password incorrentBackUsername not found or password incorrentBackUsername not found or password incorrentBackUsername not found or password incorrentBackUsername not found or password incorrentBackIt scanned the whole database. Is there a way so that it does not echo it all?

Link to comment
Share on other sites

<link rel="stylesheet" type="text/css"href="/style/test.css" /><?php $con = mysql_connect("localhost","****","****");if (!$con)  {  die('Could not connect: ' . mysql_error());  }    mysql_select_db("shackguys", $con);$result = mysql_query("SELECT * FROM accounts");while($row = mysql_fetch_array($result)){    if ( $_POST[uname]==$row['uname'] )  {setrawcookie("user", $_POST['uname'], time()+1800);echo "Congratulations $_COOKIE[user] you have logged in.<br>  <a href='./console.php'>Click Here</a> to continue.";  }else  {  echo "Username not found or password incorrent<br><a href='./console.php'>Back</a>";  }}?>

Link to comment
Share on other sites

<?php$con = mysql_connect("localhost","****","****");if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("shackguys", $con);$result = mysql_query("SELECT * FROM accounts");while($row = mysql_fetch_array($result)){if ( $_POST[uname]==$row['uname'] ){setrawcookie("user", $_POST['uname'], time()+1800);echo "Congratulations $_COOKIE[user] you have logged in.<br><a href='./console.php'>Click Here</a> to continue.";}else{}}?><?php echo "<br><a href='./console.php'>Back</a>" ?>

I hope that this can help you .

Link to comment
Share on other sites

Instead of getting every single account from the database, just get the one you're interested in and check the password. In your original code you're not even checking the password either, if they type a username they get in.

$result = mysql_query("SELECT password FROM accounts WHERE uname='" . mysql_real_escape_string($_POST['uname']) . "'");if($row = mysql_fetch_array($result)){  if ( $_POST['password'] == $row['password'] )  {	setrawcookie("user", $_POST['uname'], time()+1800);	echo "Congratulations {$_POST['uname']} you have logged in.<br>	<a href='./console.php'>Click Here</a> to continue.";  }  else  {	echo "Incorrect password";  }}else{  echo "Username not found";}

Also, it's not a great idea to have a cookie with just the user's name and nothing else. It's easy to create your own cookies. That means I could create a cookie called "user" with your domain on it and give it the value "admin" and then I'm logged in as admin. If you want to use cookies, then you'll need to think of a way to encode a password in the cookie as well. Like combine the user's password from the database with the user's IP address and hash it all together and save that hash in the cookie. Then at least you can be reasonably sure that someone didn't just steal someone else's cookie, because it would be tied to a specific IP. It might be better to just use the session instead of cookies.

Link to comment
Share on other sites

I'v only just begun using cookies so i have no idea on encoding them or hashing them, also this is the first time i'v run anything using user loging's, and luckily there is no admin username :)

Link to comment
Share on other sites

<?php$con = mysql_connect("localhost","****","****");if (!$con){die('Could not connect: ' . mysql_error());}mysql_select_db("shackguys", $con);$result = mysql_query("SELECT * FROM accounts");while($row = mysql_fetch_array($result)){if ( $_POST[uname]==$row['uname'] ){setrawcookie("user", $_POST['uname'], time()+1800);echo "Congratulations $_COOKIE[user] you have logged in.<br><a href='./console.php'>Click Here</a> to continue.";}else{$number=1;			if($number==1){			echo "username or password not correct";			$number++; //I am not sure but about this incrementing but you shoud check this syntax			}   		}}?><?php echo "<br><a href='./console.php'>Back</a>"; ?>

Link to comment
Share on other sites

Thanks. justsomeguy <- This is the way how did i understand him His code does not check cookie for username and passwords he just told you to add that .And he recommend you to make your own cookie for that . Because he could make a cookie to enter your database like an Admin and delete your database but he is nice guy and wont do that :) . I hope so .

Link to comment
Share on other sites

I'v only just begun using cookies so i have no idea on encoding them or hashing them
That's why I was suggesting to use sessions instead. If you want to use a cookie then you could create the cookie like this for the password after getting it from the database:
$pass = sha1($row['password'] . $_SERVER['REMOTE_ADDR']); // create a hash of the password and IPsetcookie("password", $pass, time() + 1800);

When the user comes back you check their cookie against the database password and their IP, so you look up their password based on the username in the cookie and then create the hash again and make sure it matches. If it doesn't match, make them log in again.

$require_login = true;if (isset($_COOKIE['uname'])){  $result = mysql_query("SELECT password FROM accounts WHERE uname = '" . mysql_real_escape_string($_COOKIE['uname']) . "'");  if ($row = mysql_fetch_assoc($result))  {	$pass = sha1($row['password'] . $_SERVER['REMOTE_ADDR']);	if ($pass == $_COOKIE['password'])	  $require_login = false;  }}if ($require_login){  header("Location: login.php");  exit();}

They will have to log in again if their IP changes, but that's the price you pay when you use cookies.

Link to comment
Share on other sites

$require_login = true;if (isset($_COOKIE['uname'])){  $result = mysql_query("SELECT password FROM accounts WHERE uname = '" . mysql_real_escape_string($_COOKIE['uname']) . "'");  if ($row = mysql_fetch_assoc($result))  {	$pass = sha1($row['password'] . $_SERVER['REMOTE_ADDR']);	if ($pass == $_COOKIE['password'])	  $require_login = false;  }}if ($require_login){  header("Location: login.php");  exit();}

They will have to log in again if their IP changes, but that's the price you pay when you use cookies.

Why do you think that he can use this in his code .? Can you explain how to use this is his code ?Or I total miss understand you .
Link to comment
Share on other sites

That code can go on the top of any page that needs to be password-protected. It will check the cookie to see if someone is logged in and send them back to login.php if they aren't. The first piece of code where the cookie is set goes with the other code that already sets the uname cookie, and the second piece of code can go on any page that needs to check for a user.

Link to comment
Share on other sites

well i'm not password protecting pages, all that i'm doing is getting the user's data so that it can be used in a small box in the top corner that will display some things depending on what the user has signed up for.while on that topic, any idea why anything below the welcome line is not showing up?

<?php if ($_COOKIE['user']== "")  echo "Welcome Guest.<br>  Please <a href='./login.html'>Log In</a>";  else{  echo "Welcome " . $_COOKIE['user'] . "<br>";  $query = "SELECT * FROM accounts WHERE uname = '" . mysql_real_escape_string($_COOKIE['user']) . "' AND password = '" . mysql_real_escape_string($_COOKIE['password']) . "'";// Perform Query$result = mysql_query($query);while($row = mysql_fetch_array($result))	{if ($row['sgradio']=="y")	echo "<h1>Welcome to the ShackGuys Radio. Playing non-stop music all day.</h1><OBJECT ID='MediaPlayer1' CLASSID='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' CODEBASE='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab# Version=5,1,52,701' STANDBY='Loading Microsoft Windows® Media Player components...' TYPE='application/x-oleobject' width='0' height='0'><param name='fileName' value='http://shackguys.servegame.org:8000/shackguys.m3u'><param name='animationatStart' value='true'><param name='transparentatStart' value='true'><param name='autoStart' value='true'><param name='showControls' value='true'><param name='Volume' value='-300'><embed type='application/x-mplayer2' pluginspage='http://www.microsoft.com/Windows/MediaPlayer/' src='http://shackguys.servegame.org:8000/shackguys.m3u' name='MediaPlayer1' width=0 height=0 autostart=1 showcontrols=1 volume=-300></OBJECT><br><a href='./logout.php'>Log Out</a><br>";else  {  echo "You are not subscribed to the radio. To listen please <a href='./radio/' target='_blank'>click here</a><br><a href='./logout.php'>Log Out</a><br>";	}	}	}?>

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...