hello Dany web friends
how to use cookies session in php, how to insert cookie in database table to rember user,
i would like to rember what page a user viewed on my website... and i think i can use cookie for SESSION but i don't know how to use.

Recommended Answers

All 24 Replies

Member Avatar for diafol

Sessions and cookies in this context have different uses. A cookie will sit on the user's machine for the duration stipulated in setcookie or until it is wiped/overwritten by the site or cleared manually by the user. A session cookie on the other hand is pretty much done once the session is done. You do not want to store any sensitive data in a cookie, ever.

Before you start implementing 'save my details', consider all the security implications involveed with providing this type of convenience.

Your implementation will probably revolve around producing a time-dependent token. There are many links out there about this functionality, but be aware, not all of them are secure. If you can't find a suitable tutorial, come back.

the explication is litle complicate please try undestund me thank you.
i have made many research on web about cookies, i have idea how it work but i don't know how to use it for my requirement.
what i realy want do is:
i user will submit a form wich contain a title , a description. user id, insert it in data base. i want use cookies for temporary user who don't have acoount on my website.
and i want my website rember the user (temporary visitor ) when he comme back 8 days, and get data from database when cookies = with user session cookies
i don't know if you undestund what i mean., on my website i use START SESSION TO KEPP USER LOG IN , how i will use session for cookie.

You can't use anything on a session for 8 days. It'll expire as soon as the user closes the browser, or at the session expire limit.

When you say the user submits a form containing title, description, and user id: How is the user id generated for temporary users? I would suggest making this a hash to avoid easy UID hijacking and then storing it in a cookie on the user's browser, which will be about as secure as PHP's session IDs. For that you'll need setcookie() and then $_COOKIE to read it.

Lsmjusdoka your answer is helpfull. please read this exemple
in this exmple i insert the form in database table $_SESSION['MM_Username'] is connected user email.

  <form action="<?php echo $editFormAction; ?>" method="POST" name="achat" class="formaddto">
          <input  type="hidden" name="client" id="client" value="<?php echo $_SESSION['MM_Username']; ?>">
          <input name="article"  type="text" class="addto" id="article" value="<?php echo $row_a10['titre']; ?>" readonly>
          <input name="prix"  type="text" class="addto" id="article" value="<?php echo $row_a10['prix']; ?>  EUR " readonly>
          <input  type="hidden" name="sku" id="sku" value="<?php echo $row_a10['sku']; ?>">
          <input  type="text" name="quantite" id="quantite" value="1">
          <input name="adcart" type="submit" class="boutonaddto" id="adcart" value="ADD TO CART">
           <button type="submit" class="boutonaddto" name="adcart" value="ADD TO CART"><img src="images/shopping-cart-icons.png" width="38" height="31" /></button>
          <input type="hidden" name="MM_insert" value="achat">
        </form>

but now i want the same for temporary visitor (user ) remplace the $_SESSION['MM_Username'] with cookies and read it later like i do with connected user here is the php and mysql coe

mysql_select_db($database_DB, $DB);
$query_panier = sprintf("SELECT panier.id,panier.quantite,panier.client,  phone.titre,panier.sku, phone.prix,phone.shipping,(panier.quantite*phone.prix) AS subtotal FROM panier INNER JOIN  phone ON panier.sku=phone.sku WHERE panier.client=%s", GetSQLValueString($paramclient_panier, "text"));
$panier = mysql_query($query_panier, $DB) or die(mysql_error());
$row_panier = mysql_fetch_assoc($panier);
$totalRows_panier = mysql_num_rows($panier);

$paramclient_total = "0";
if (isset($_SESSION['MM_Username'])) {
  $paramclient_total = $_SESSION['MM_Username'];

What is a typical or example value for $_SESSION['MM_Username'] and is that ever shown to the user?

it is the connected user email, i user $_SESSION['MM_Username'] to insert connected user email in database and for read if actual session = to to user in database,

need help here can some body help me???

If $_SESSION['MM_username'] is never shown to the user then for temp users you can use a different value there. Instead of the email they haven't provided, use an md5 hash of a random number, just make sure to double-check the DB and see that someone else hasn't already rolled that number. Then store the has in a cookie in their browser.

how i can do it i'm not prefesional in php,
i want use cookies to realise the same like the up exemple

Aside Note

Check CodeIgniter (CI) framework you can find an example of what you want to achieve, refer to their session library, here you can find the documentation:

Basically they do what Lsmjudoka is suggesting, so you have to create a table like this one:

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

Where the session_id changes every five minutes (they allow you to set the time), and saves the new cookie to the client. The column user_data is used to store a serialized array of each element you want to load in session, this gives you the ability to save whatever you want, even a user_id if, for example, you want to refer the session to a registered user.

Keep in mind, that if the session_id is predictable an attacker can send a cookie with the value and gain access and this is why diafol suggested you:

Before you start implementing 'save my details', consider all the security implications involveed with providing this type of convenience.

In CodeIgniter they also encrypt the cookie, so the session_id is not directly exposed, and this gives a bit more security to the application. If you want to create your own system then try to read through their code it will help you to understand all the steps of this system.

I'm suggesting this because CI is a real world application, but you can still search for tutorials or others frameworks which offers such functionality. Good work!

i don't undestund, all that i try read the url you give but still i can't undestund.
the only thing i want to do is to remplace to $SESSION['Username'] with a cookie session.

The part of the code you need to replace is the one where existing users log in. I haven't seen in the examples you post where you process their log in, but you'll just create a separate branch that:

1) Hashes a random number $hash = md5(mt_rand(1, 1000000));
2) Checks your database to ensure there's no collision

$result = mysql_query("SELECT id FROM panier WHERE client='$hash' LIMIT 1");
if(mysql_num_rows($result) == 1) {
    // Repeat step 1
}

3) Inserts the new hash into the session(for immediate use), a long-lasting cookie, and your database. The cookie is what you'll check the next time they come back to the page. Something like

if(!isset($_SESSION['MM_username']) && isset($_COOKIE['MM_username'])) {
    $_SESSION['MM_username'] = $_COOKIE['MM_username'];
}

If you can post the login code I'll be able to offer more input on where exactly this code would go.

i insert in data base in colum usercookies i get something like this "2d391d4cc8562ec6af137a68f944393a" "3658616e9881325b96dc3b53c6e37e68" so every time have different valut, how can i do for every computer to inser every time same $hash, be cause i want to collect it back to this way

<?php
$usercookies_paniertest = "0";
if (isset($hash)) {
  $usercookies_paniertest = $hash;
}
mysql_select_db($database_connect, $connect);
$query_paniertest = sprintf("SELECT * FROM paniertemporaire WHERE paniertemporaire.usercookie=%s", GetSQLValueString($usercookies_paniertest, "text"));
$paniertest = mysql_query($query_paniertest, $connect) or die(mysql_error());
$row_paniertest = mysql_fetch_assoc($paniertest);
$totalRows_paniertest = mysql_num_rows($paniertest);
?>

hello my friends i need help here :)

Write your code so that you check to see if the hash is already in a cookie in the user's browser. If it is, select the matching row from the DB. If not, insert a new row into the DB and set the new randomly generated hash into the cookie.

hello dear friend
i have try to refresh page and refresh page every time i refresh the hash change i want same hash for a pc ... how can i do it .. i never use cookies in my life ... can i do it with set cookies??? and how????

Indeed you need setcookie to set the cookie: http://php.net/setcookie
Then you can check if the cookie has been set using the superglobal $_COOKIE array. Basically-

Setting cookie (for 30 days):
setcookie("MM_username", $hash, time() + (86400 * 30));

Checking cookie:
if(isset($_COOKIE['MM_username'])) {

i used this and i thiked it will work but nothing

$value = '$hash';
setcookie("usercokies", $value);
setcookie("usercookies", $value, time()+3600);  /* expire dans 1 heure */
setcookie("usercookies", $value, time()+3600, "/~rasmus/", "localhost/henrybusiness", 1);
 ?>

and in form i use <?php echo $value; ?> what i get is $hash i get $hash in DB

You don't need to call setcookie() 3 times, only once. Also I'm ~90% sure that by including the 4th parameter "/~rasmus/" you're pointing to a path on your server that does not exist, unless you actually have a ~rasmus directory. The 4th parameter is the path, 5th parameter is the domain name. Both are optional, for your testing purposes I would exclude them.

Additionally what you need from a structure standpoint is to lay out the if/else rules for when it runs.

If the user logs in, this(setting new cookie) should not run.
If the user does not have an account and is a temp user, you need to check $_COOKIE to see if the cookie is already set (e.g. they have come to the site before)
If they have no account and there is no cookie, then you set the cookie.

Make sure the name you set in setcookie() is the same one you use in $_COOKIE. Meaning you used 'usercookies' in your example, so you would access the cookie through $_COOKIE['usercookies']

sorry to don't reply that long time i worked on design part of my website.
thank you for your help ... it is my first time to use cookie i'm not good programmer i don't undestund realy what i must edit can you please write with my code???

can you please write with my code???

what?????? it is like:

hey i cant build a house, will you build one for me :P

just google about cookie and sessions you will find a lot of better tutorial.
also you will find a lot of better examples and demos. dont ask for writing your code??
show us what you have tried, we can help you then.

MERY CHRISTMAS FRIENDS
i thing i'm loose in all.
i use $_SESSION['MM_username'] for loged in user username (email).
in this

<?php $hash = md5(mt_rand(1, 1000000)); 
  if(!isset($_SESSION['MM_username']) && isset($_COOKIE['MM_username'])) {
    $_SESSION['MM_username'] = $_COOKIE['MM_username'];
}
  ?>

i want just to remember temporary user to add item in shopping cart in next page i will lect all data in table where colum user = $hash
and place order insert data in another table.... there i will not use $hash i will use $_SESSION['MM_username'] there user must log in to place a order.
I HOPE YOU UNDESTUND WHAT I MEAN.
where is the problem now with the up code ????? when i add item in a database table i i use $hash for user i get a gerated characte number ...abcde.... so the md5 but every time when i insert it generate new.
and when i select* from table whre colum user= $hash it don't find anything in table.. cause every time it generate new hash code (md5)

hello friend.
i know i if you want build a house, it is not possible i build one for you (haha i undestund what you mean) and i'm sorry for it my mistake sometime :D.
anyway i still suffer in with the same problem.
i have this code for generating the hash code

  <?php 
      $hash = md5(mt_rand(1, 1000000));
      $result = mysql_query("SELECT id FROM dbtable WHERE client='$hash' LIMIT 1");
if(mysql_num_rows($result) == 1) {
    // Repeat step 1
    $hash = md5(mt_rand(1, 1000000));
    }
    if(!isset($_SESSION['MM_username']) && isset($_COOKIE['MM_username'])) {
    $_SESSION['MM_username'] = $_COOKIE['MM_username'];
}
?>

it work fine it generate beatyfull md5 hash code but what i want is to generate same md5 hash code for same visitor to remember him late i want save the md5 hash in database to to remeber temporary visitor for 1 moth.
so i don't know how tryed to place this cookie code on top of my page but nothing change

<?php setcookie("MM_username", $hash, time() + (86400 * 30));
if(isset($_COOKIE['MM_username'])) { 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.