Jump to content

Recommended Posts

Yep, I have no idea of how to use cookies. I am even making my own forum, knowing how to use cookies.

 

Basically, I have the loggin form that stores the user id, his name, and a unique user hash.

 

<?php

$_SESSION['login'] = $username;
$_SESSION['id'] = $id;
$_SESSION['hash'] = $hash;

?>

 

I also want the cookie to expire after a month.

 

Every tutorial I have read about this is confusing, so maybe if I do it with that I will understand cookies.

Link to comment
https://forums.phpfreaks.com/topic/122986-how-do-i-make-a-basic-cookie/
Share on other sites

Those you're using are sessions. Cookies can be registered like this:

 

<?php
setcookie('name', 'value', time()+60*60); //set the cookie 'name' with a value of 'value' for 1 hour  (60sec*60min)
setcookie('login', $username, time()+60*60*24*31); //set it to expire in one month
echo $_COOKIE['login']; //print the cookie
?>

 

They are pretty simple so I wonder what problems did you have with "confusing" tutorials.

 

If you want to use sessions in your code, place a session_start() in the first line of the script, or your sessions won't register.

Cookies are used to store data.  The data you store (and retrieve when they return) let's you determine whether or not they are authenticated.  It depends on what data you want to store, and how you want to handle it.

 

If you had a simple login, you could store a simple cookie like such when they logged in:

<?php
//upon successful login
setcookie('login', "$username|yes", time()+60*60*24*31); //set it to expire in one month
?>

 

And later when they revisit the page:

<?php
if(isset($_COOKIE['login'])){
  $info = split('|',$_COOKIE['login']);
  
  if($info[1] == 'yes'){
    $username = $info[0];
    //set logged in = true, or w/e you do to login
  }
}
?>

 

That is an INSECURE and BASIC example.  You shouldn't trust cookie data like that at all... I'm just using it to illustrate the concept.  It's more common to save the username and have it already entered into a login form so they just have to enter a password.

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.