0

I am trying to use cookies to maintain log-in persistence on my website. But, for some reason unknown to me, the cookie is not being created. Only the Session is being created. I am using Sessions to keep track of the logged in user, and cookies to re-create the session when they come back. What am I doing wrong?

Create the session and cookie:

<?php $connect= // connect variables $query= "SELECT * FROM users where email= '$email' AND password= '$password'"; $result= mysqli_query($connect, $query) or die('error with query'); if (mysqli_num_rows($result) == 1) { $row= mysqli_fetch_array($result); session_start(); $_SESSION['id']= $row['user_id']; $_SESSION['name']= $row['fname'] . " " . $row['lname']; setcookie('id', $row['user_id']); $profile_url= 'http://'. $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/profile.php'; header('Location:profile.php'); } else { $message= "Incorrect email/password combination."; } ?> 

Check for a cookie to restore the session:

<?php session_start() /* if a session does not exist, see if a cookie does to set the session */ if (!isset($_SESSION['id'])) { if (isset($_COOKIE['id'])) { $_SESSION['id'] = $_COOKIE['id']; } else { } } ?> 

EDIT

I needed to add an expiration parameter to the cookie!

setcookie('id', $row['user_id'],time()+86400); Note: The above example sets the cookie for 1 day 
1
  • Sorry :S Didn't know there was a timer :o Commented Jan 15, 2013 at 23:49

3 Answers 3

5

Cookie is created, but you create it for 0 seconds. Third parameter is $expire, use it...

http://php.net/manual/en/function.setcookie.php

$expire quote

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! Condescending or not! :)
3

You are missing a few things here (expiry,path,domain):

setcookie('id', $row['user_id'],time()+86400,"/",".your_domain.com"); 

Note: The above example sets the cookie for 1 day in the root of the domain, for the domain "your_domain.com". Now thats a lot of domains!

Comments

2

I needed to add an expiration date to the cookie.

setcookie('id', $row['user_id'],time()+86400); 

1 Comment

+1 @minitech Thanks for pointing out my mistake. I didn't notice it was the asker.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.