Jump to content

setting a cookie


squigs

Recommended Posts

Hello,

My latest issue is with a login page I am trying to set a cookie for. I have deduced that it it pulling my info out of my database correctly. It does not give any errors for username or password when they are entered correctly but when I get to the end of the script where I would like to set a cookie and redirect to a new page it just stays on the same page and appears as if it is loading but nothing happens.

 

After I stop the browser and attempt to reload the page it gives me an error saying the page cannot be displayed.

 

Do I need to specify anything before I can have the following code work or is it that it is clashing somewhere else along the way?

 
<?php
else 
{ 
// if login good set cookie
$_POST['username'] = stripslashes($_POST['username']);   
$hour = time() + 3600; 
setcookie(ID_my_site, $_POST['username'], $hour); 
setcookie(Key_my_site, $_POST['pass'], $hour); 
//then redirect them to the members area 
header("Location: http://example.com/");
die();
}  
?>

 

If I remove this code and simply leave the redirect as shown above, it works. But that defeats the purpose of the script as on the redirected page there has to be a cookie set to display it.

 

Any help would be appreciated

Link to comment
Share on other sites

Nothing happens if I remove the die(). It was more just me playing around with that made me add it. I have figured out that this script does seem to be working somewhat, I set it up to redirect me to a members area which at the moment I'm just testing for proper code.

 

The code on this page looks something like this.

<?php 
mysql_connect("servername", "name", "password") or die(mysql_error()); 
mysql_select_db("whatever_db") or die(mysql_error());
//checks cookies to make sure they are logged in 
if(isset($_COOKIE['ID_my_site'])) 
{ 
$username = $_COOKIE['ID_my_site']; 
$pass = $_COOKIE['Key_my_site']; 
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); 
while($info = mysql_fetch_array( $check )) 
{ 

//if the cookie has the wrong password, they are taken to the login page 
		if ($pass != $info['password']) { 	
	header("Location: login/admin_login.php");} 


//otherwise they are shown the admin area	  
		else	{
echo "Admin Area<p>"; 
echo "Your Content<p>"; 
echo "<a href=logout.php>Logout</a>"; 		  
		}
	}
		} 
else 

//if the cookie does not exist, they are taken to the login screen 
{			 
die ('you suck2');
} 
?> 

 

I keep making changes hoping to see the echo commands but it continually tell me I suck... Kinda hard on the ego really.

 

Anyways I can't figure out if its not setting the cookie properly or if something else here is wrong.

 

This posted script is currently standing alone in a .php file while the one posted in my previous post has the

<?php ?> code all in the head of my page.. Well most of it anyways, there are a couple includes in the body just for sidebar styling etc.

Link to comment
Share on other sites

[EDIT] I really need to type quicker, it is on my to do list,  where ever that is nowadays...

 

$_POST['username'] = stripslashes($_POST['username']);   
$hour = time() + 3600; 
setcookie(ID_my_site, $_POST['username'], $hour); 
setcookie(Key_my_site, $_POST['pass'], $hour); 
//then redirect them to the members area 
header("Location: http://example.com/");
die();

 

Seriously this is a bad way of doing this, firstly, if you had error reporting on you would get an error saying something like: presumed constant.  Reason being, the name your assigning to your cookie hasn't been quoted and therefore is acting like a constant !ACTING! php will treat this as missing/not defined and throw the error.

 

Also, your not specifying a the time limit correctly, though, not wrong, just un-necessary use of memory to assign the time to a var, this should be done within the function.

 

Lastly, specify the domain that you want the cookie active on, using the "/" method will save a lot of time.

 

so do something like this:-

 

setcookie("ID_my_site", stripslashes($_POST['username']), time()+60*60*24*30, "/"); 
setcookie("Key_my_site", stripslashes($_POST['pass']), time()+60*60*24*30, "/"); 
//then redirect them to the members area 
header("Location: http://example.com/");
exit;

 

Ok, they are defined better now, cookies are set for 30 days throughout your domain!

 

Simple.

 

Rw

Link to comment
Share on other sites

<?php include ('../../Connections/login_db.php');?>
<?php 
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{ $username = $_COOKIE['ID_my_site']; 
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check )) 
{
if ($pass != $info['password']) 
{
}
else
{
header("Location: ../members.php");

}
}
}
//if the login form is submitted 
if (isset($_POST['submit'])) { 
// if form has been submitted
// makes sure they filled it in
if(!$_POST['username'] | !$_POST['pass']) {
die('You did not fill in a required field.');
}
// checks it against the database

if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database. 
<p><a href=add.php>Click Here to Register</a>');
  }
  while($info = mysql_fetch_array( $check )) 
  {
  $_POST['pass'] = stripslashes($_POST['pass']);
  $info['password'] = stripslashes($info['password']);
  $_POST['pass'] = md5($_POST['pass']);
  
  //gives error if the password is wrong
  if ($_POST['pass'] != $info['password']) {
  die('Incorrect password, please try again.');
  }
else 
{ 
// if login is ok then we add a cookie 
$_POST['username'] = stripslashes($_POST['username']); 
$hour = time() + 3600; 
setcookie(ID_my_site, $_POST['username'], $hour); 
setcookie(Key_my_site, $_POST['pass'], $hour); 

//then redirect them to the members area 
header("Location: ../members.php"); 
} 
} 
} 
else 
{ 
// if they are not logged in 
?>
  </head>
<body>
<div id="container">
<div id="header"><?php include ("../../login_header.php") ?></div>
<div id="photoNav"><?php include ("../../mainNav.php") ?></div>
<div id="tableContent">
<form action="" method="post"> 
<table border="0" align="center"> 
<tr><td colspan=2><div class="bold_14" style="padding-bottom:20px;">Please enter your login information</div></td></tr> 
<tr><td>Username:</td><td> 
<input name="username" type="text" size="23" maxlength="40"> 
</td></tr> 
<tr><td>Password:</td><td> 
<input name="pass" type="password" size="24" maxlength="50"> 
</td></tr> 
<tr><td colspan="2" align="right"> 
<input type="submit" name="submit" value="Login"> 
</td></tr> 
</table> 
</form> 
<?php 
} 

?>   

 

This is it plus the form where one would have to log in

Link to comment
Share on other sites

This is what I'm stuck at no matter what I try...

<?php
//if the cookie does not exist, they are taken to the login screen  
{			  
die ('you suck2'); 
}  ?> 

I changed it from a header(location:)  to die('you suck') because otherwise it sticks me in an endless loop.

Its like the login pages recognizes the cookie and redirects me to the members area which does not recognize the cookie so sends me back to the login page...

an endless cycle...

Link to comment
Share on other sites

It his is how I set my cookie

setcookie("ID_my_site", stripslashes($_POST['username']), time()+60*60*24*30, "/"); 
setcookie("Key_my_site", stripslashes($_POST['pass']), time()+60*60*24*30, "/"); 

Then what would the best way to say if the cookie does not exist then

header ('location: http://example.com/');  ?

 

Also when setting my domain in the above code could I and would it be beneficial to write in whole my domain name?

Link to comment
Share on other sites

nope still not working. Why won't this work??? Even after I delete my cookies and restart my browser to test it the die() message still appears.

 

<?php

if (isset ($_COOKIE['ID_my_site'])) 
{ 
	$username = $_COOKIE['ID_my_site']; 
	$pass = $_COOKIE['Key_my_site']; 
	 	$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); 
	while($info = mysql_fetch_array( $check )) 	 
		{ 
//if the cookie does not exist, they are taken to the login screen 
if (!empty ($_COOKIE['ID_my_site'])) 
{
header ('location: login/admin_login.php');
}

//if the cookie has the wrong password, they are taken to the login page 
if ($pass != $info['password']) 
			{ 			header("Location: login/admin_login.php"); 
			}  
//otherwise they are shown the admin area	 
	  
		}  
		} 
else 


{			 
die("you suck"); 
} 
?> 

Link to comment
Share on other sites

That is all of my code on this page which is an admin page.

 

I have posted earlier in this topic the code I am using to set the cookie.

 

I am receiving no errors at this point. Basically I will know it is working when I try to load this page directly with no cookies saved in my browser and it redirects me to the login page where I can enter my username and password and then be redirected back to the admin page and see the 'you suck' message

Link to comment
Share on other sites

here is the code supposed to set the cookie

<?php include ('../../Connections/login_db.php');?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php 

if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{ $username = $_COOKIE['ID_my_site']; 
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check )) 
{
if ($pass != $info['password']) 
{
die ('blah');
}
else
{
header ('location:../admin.php');

}
}
}
//if the login form is submitted 
if (isset($_POST['submit'])) { // if form has been submitted

// makes sure they filled it in
if(!$_POST['username'] | !$_POST['pass']) {
die('You did not fill in a required field.');
}
// checks it against the database

if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database. 
<p><a href=add.php>Click Here to Register</a>');
  }
  while($info = mysql_fetch_array( $check )) 
  {
  $_POST['pass'] = stripslashes($_POST['pass']);
  $info['password'] = stripslashes($info['password']);
  $_POST['pass'] = md5($_POST['pass']);
  
  //gives error if the password is wrong
  if ($_POST['pass'] != $info['password']) {
  die('Incorrect password, please try again.');
  }
else 
{ 
// if login is ok then we add a cookie 
setcookie("ID_my_site", stripslashes($_POST['username']), time()+60*60*24*30, "/"); 
setcookie("Key_my_site", stripslashes($_POST['pass']), time()+60*60*24*30, "/"); 
//then redirect them to the members area 
header("../admin.php");
exit;
} 
} 
} 
else 
{ 
// if they are not logged in 
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow"/>
<title>Administrator logon</title>
<link href="../../page.css" rel="stylesheet" type="text/css" />
  </head>
<body>
<div id="container">
<div id="header"><?php include ("../../login_header.php") ?></div>
<div id="photoNav"><?php include ("../../mainNav.php") ?></div>
<div id="tableContent">
<div class="bold_16" style="margin-top:40px">Administrator Login</div>
<div class="padding_top"><div style="padding-top:10px; text-align:center;">

</div>

<form action="" method="post"> 
<table border="0" align="center"> 
<tr><td colspan=2><div class="bold_14" style="padding-bottom:20px;">Please enter your login information</div></td></tr> 
<tr><td>Username:</td><td> 
<input name="username" type="text" size="23" maxlength="40"> 
</td></tr> 
<tr><td>Password:</td><td> 
<input name="pass" type="password" size="24" maxlength="50"> 
</td></tr> 
<tr><td colspan="2" align="right"> 
<input type="submit" name="submit" value="Login"> 
</td></tr> 
</table> 
</form> 
<?php 
} 

?>   

Link to comment
Share on other sites

Since you are outputting the DOCTYPE and HTML and HEAD tags at the beginning of that script, the setcookie() and header() functions are going to fail. If you had error reporting turned on, you would get a message about headers already sent when you call those functions.

Link to comment
Share on other sites

When we write about error_reporting being turned on, we are referring to setting it to at least E_ALL and since that doesn't include E_STRICT or E_DEPRECATED, you should actually set it to -1 so that all the bits are set. Error_reporting should always be set to at least E_ALL (even on a live server.)

 

Setting display_errors to ON will help you by giving immediate feedback because the error messages will be output to the browser. display_errors should be ON for a development system and OFF for a live server. log_errors should be ON for a live server.

Link to comment
Share on other sites

I do not get an error in my error logs however that was just me messing around I had it originally so that the <html> and <head> came afterwards however My page gets caught up in an endless loading phase and never goes anywhere.. Also I notice that my header('location:') is also wrong on the code I posted I am just messing with different things to get a better idea.

 

Please note that I have made these corrections and am stuck with a forever loading page.

 

And also thanks for your input on this, I;m pulling at my hair.

Link to comment
Share on other sites

When we write about error_reporting being turned on, we are referring to setting it to at least E_ALL and since that doesn't include E_STRICT or E_DEPRECATED, you should actually set it to -1 so that all the bits are set. Error_reporting should always be set to at least E_ALL (even on a live server.)

 

Setting display_errors to ON will help you by giving immediate feedback because the error messages will be output to the browser. display_errors should be ON for a development system and OFF for a live server. log_errors should be ON for a live server.

 

I guess I should contact my server admin for changes to my php.ini file?

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.