Jump to content

setcookie...output problem


jimfog

Recommended Posts

I am trying to set up a persistent login mechanism where I have to cal setcookie/session start before any output. The problem is that, the way I see it output, will come out soon, either way,let me explain:

  if(!empty($_POST['remember']))     {     $conn=db_connect();     $identifier=uniqid();     uniqid_to_db($identifier);     setcookie('cookiename', $identifier, time() + 60 * 60 * 24 * 7, '/', '' , true);     }session_start();?>  

I mean that the code is separated into 2 bockls, whether the user ticked the remember me option and when not.If the user did not then not setcookie will be called,here, in this case no output is produced-BEFORE sessionstart() is called- so we do not have problem here. But, when the user ticks the remember me option output HAS to be produced-that is located BEFORE sessionstart() in the code and as a result the familiar message "headers already sent" appears. It should be sth easy to fix-I am just confused a little. The problem is placing the code in the proper place in the script, something which depends when setcookie/sessionstart gets called. I want to avoid producing the whole output of the page, when remember me is ticked and when not, using an if...else statement I hope I was clear...if not, ask more info.

Link to comment
Share on other sites

Why? That sounds like a problem in your design.
Yes I have a problem in my design/logic. WHat I am trying to do-in a few words- is that I am trying to fit in a script the login form, the if statement that it was filled and an if statement that checks if a cookie has been set in the user's computer. I have managed the first 2 but I am having difficulty with the setcookie if statement as there is the constraint that this has to be done before any output sent. here is some code-not complete:
<?php session_start();require 'userauth_admin.php';	 if(!empty($_POST['remember']))	 {	 $conn=db_connect();	 $identifier=uniqid();	 uniqid_to_db($identifier);	 setcookie('cookiename', $identifier, time() + 60 * 60 * 24 * 7, '/', '' , true);	 }?> 	  <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">    <head>	    <title></title>	    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />		 <link rel="stylesheet"  href="css/admingeneral.css"/>	    <script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" ></script>	    <script type="text/javascript" src="js/js-code.js"></script>    </head>   <body>		   	 <div id="wrap">      <?php		  require 'output_functions_admin.php';	  	     try  {  if (isset($_POST['username'])&& (isset($_POST['password'])))	   	   { if(empty($_POST['username'])&& (empty($_POST['password'])))	    {	  throw new Exception('Ουπς, δεν συμπληρώσατε τα στοιχεία -πίσω στην φόρμα λοιπόν για να τα συμπληρώσετε.');	    }		 else	    {		 $username = $_POST['username'];		 $passwd = $_POST['password'];		 if (login($username, $passwd)) {			 $_SESSION['valid_user'] = $username;		  output_header('output_header_list',$username);		  		 		  ?>	    <div id="cust_icon"><img src="Images/administrator_40.png" alt="customers" /></div>		  <?php		 		  //output_customers();		  output_buttons();			 }			    ?><div id="leftcolumn" align="center">   <div id="calendar_div" name="calendar_div">  <?php output_leftside_cal(date('n',strtotime($newdate)),date('n',strtotime($newdate)),date('Y',strtotime($newdate)));  ?></div>	 	   <?php output_leftbuttons(); ?>	  </div>		  <div id="timeslots">			    <?php output_day();?>		   </div>		   	 <?php		 		 }	    }    else    output_login_form();    }

sorry for the much code.

Link to comment
Share on other sites

well, what is missing above(and the one that I do not know how to implement it ) is an if statement that checks if there is a cookie in the user's computerand act appropriately depending on that fact. If there is not a cookie, I go and set one(the code is ready for that-it is in the very beginning of the script). The problem is how implementing the if logic IF there is already a cookie in the user's computer.The problem is that I must take into consideration that this must be done before output. How am I going to do this if statement-integrating it to the one above?

Link to comment
Share on other sites

I can't see any difficulty in checking for a cookie:

if(isset($_COOKIE['something'])) {    $cookievalue = $_COOKIE['something'];} else {    $cookievalue = 'value';    setcookie( 'something', $cookievalue, ... ... );} // The variable $cookievalue can now be used anywhere in the page

Link to comment
Share on other sites

I can't see any difficulty in checking for a cookie:
if(isset($_COOKIE['something'])) {	$cookievalue = $_COOKIE['something'];} else {	$cookievalue = 'value';	setcookie( 'something', $cookievalue, ... ... );} // The variable $cookievalue can now be used anywhere in the page

Where the html will go-cause I said, if a cookie exist, the user must be directed to the member's area.Assume it will go in the first if block, prior to "else"... Let me make some tests I have in my mind and I will get back Edited by jimfog
Link to comment
Share on other sites

before proceeding at the heart of the issue, this code below does not work:

   if (isset($_COOKIE['cookiename'])) {	    echo 'hi';	 } elseif (!empty($_POST['remember']))	 {   $conn = db_connect();		 $identifier = uniqid();		 uniqid_to_db($identifier);		 setcookie('cookiename', $identifier, time() + 60 * 60 * 24 * 7, '/', '', true);	 }?> 

After setting the cookie, and the visitor coming for the second time in the site, I should geta hi string and I do't.I used fiddler, and saw that a cookie was sent, with the above name.The below statement:

isset($_COOKIE['cookiename'])

doesn't check if the specified cookie is in the user's PC?

Link to comment
Share on other sites

Are you accessing your site over HTTPS? You're telling it to only send that cookie over a secure connection.
Oh.....d..., what i was thinking?It is on localhost, I will remove that "true" and try again-I will tell if it works or not.
Link to comment
Share on other sites

Now it works...the original problem remains though, Let me do some tests, play around with the codeand I will get back If I hit a "Wall".

Link to comment
Share on other sites

This is the code in a more compact/easier to read form:

if (isset($_POST['username']) && (isset($_POST['password']))) {	  if(!empty($_POST['remember']))	  { $conn = db_connect();		 $identifier = uniqid();		 uniqid_to_db($identifier);		 setcookie('cookiename', $identifier, time() + 60 * 60 * 24 * 7, '/', '');    }			  if (empty($_POST['username']) && (empty($_POST['password']))) {			 throw new Exception('Ουπς, δεν συμπληρώσατε τα στοιχεία -πίσω στην φόρμα λοιπόν για να τα συμπληρώσετε.');		 } else {			 $username = $_POST['username'];			 $passwd = $_POST['password'];			 if (login($username, $passwd)) {				 $_SESSION['valid_user'] = $username;				 output_header('output_header_list', $username);	 ?>						 <div id="cust_icon"><img src="Images/administrator_40.png" alt="πελάτες" /></div>				 <?php				 //output_customers();				 output_buttons();				 ?><div id="leftcolumn" align="center">				    <div id="calendar_div">				 <?php output_leftside_cal(date('n', strtotime($newdate)), date('n', strtotime($newdate)), date('Y', strtotime($newdate))); ?></div>	 				 <?php output_leftbuttons(); ?>					   </div>						  					   <div id="timeslots">				 <?php output_day(); ?>						    </div>			 <?php			 }		 }	 }

The above though has a problem with the headers, as you see, since setcookie is called after the headers. So, the problem, is how, in essence, how am I going to split the code effectively, half above the headers, and half below(the html output). What makes it difficult is, the fact that, the code above is a big IF statement(whether the user filled in the form) and if I do not splitit successfully the logic will be ruined. I think, in this post, I articulate the problem much better.

Link to comment
Share on other sites

Hello, As in login page with remember me feature. If user successfully logged in the system then you will definitely redirecting user to any other page.
I was trying to make them fit everything in the same page-maybe what are you proposing is better
You can not use setcookie before header(location; index.php). It should be after header().
Are you sure about that? Session start and setcookie I think they go, before headers, unless you are referring to the function header. Thanks
Link to comment
Share on other sites

A cookie is a header, it doesn't matter if you output it before or after other headers as long as all headers go before any output. If you are redirecting then it would actually be better to set the cookie first, so that the browser sees the setcookie header and sets the cookie before it sees the location header to redirect.

The above though has a problem with the headers, as you see, since setcookie is called after the headers.
I don't see any headers before setcookie, and I don't know why you think it's a problem to use setcookie after sending headers.
Link to comment
Share on other sites

OK...now that it more clear here is my plan-and tell me if it sounds good. In one page I will put the form, with validation functions, and html output(members section)-in this page setccokie will be called if the user ticked remember me box. If a returning visitor comes here, as this will be index.php, he will be redirected the page described above.And... A second page(member's section) will again contain code relevant member's, same as above. The above is a lot of code to put in one page.Comments....?

Link to comment
Share on other sites

One correction the user will be redirected to the second page, member section, no form there or validation stuff.

Link to comment
Share on other sites

That's fine, you can break your code up using include files if you want to keep things physically separated.
Thanks for the endorsement, though.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...