Jump to content

Cookies (right direction)


whiteboikyle

Recommended Posts

Well i didn't get much help on my last post so i decided just to "JUMP" in haha can you let me know if i am doing this right and going in a right direction

 

<?php
include("config.php");

class user {
var failed = false;
var $date;
var $id = 0;

function __construct() {
	if(!isset($_COOKIE['UserSession'])){
		return "You are not logged in!";
	}
    }

function login($username = safeSQL($username), $password = md5(safeSQL($password)), $rememberMe){
	$time = time();
	$expires = 60*60*24*3; //3 Days
	$user = $config->fetch_array("SELECT * FROM `member` WHERE `username` = '$username' && `password` = '$password'");
	$userQ = safeSQL($user['username']);
	$passQ = safeSQL($user['password']);
	if($username == $userQ && $password == $passQ){
		$_SESSION['username'] = $username;
		$username = $_SESSION['username'];
		if($rememberMe){
			rememberME($username, $time);
		}
	}
	else{
		return "Username and/or Password was incorrect!";
	}
}

function rememberME($username, $time){
	$_COOKIE['UserSession'] = $username
	$config->query("UPDATE `member` SET `cookie` = '".$time."' WHERE `username` = '".$username."'");
	setcookie('UserSession', $time, $expires);	
}

function logout(){

}

function session(){

}

function register(){

}

}
?>

 

<?php
class MySQLDB
{
   var $connection;         //The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect("localhost", "root", "") or die(mysql_error());
      mysql_select_db("scripts", $this->connection) or die(mysql_error());
}
/**
    * query - Performs the given query on the database and
    * returns the result, which may be false, true or a
    * resource identifier.
    */
//Use this function as query("Query line of code");
   function query($query){
      return mysql_query($query, $this->connection);
   }
   
   function num_rows($q){
	return $config->query(mysql_num_rows($query));
   }
   
   function fetch_array($q){
	return $config->query(mysql_fetch_array($query));
   }
   
   
}

$config = new MySQLDB;
?>

Link to comment
Share on other sites

bump please i need help ASAP haha i dont wanna code something then start all over cause i did it wrong

 

Recoding because you did something wrong, is called "refactoring".  In other words, it's part of being a programmer. 

 

My main comment to you would be in your use of sessions.  Perhaps you did not know that php sessions by default and depending on configuration, already uses a cookie.  Your remember me cookie should only come into play if the person does not have a valid session state. Typically people use the existence of the cookie to do something that basically bypasses the standard username/login and authenticates the user.  This is of course a huge security hole, so you need to consider ways to insure that you'll accept this cookie.  There are a number of different schemes including: 

 

-taking the username and password and using something like mcrypt to store it in the cookie using strong encryption.

-issuing a token that is stored in relation to the user and allows them to be looked back up.  An md5 or sha1 hash of a number of elements related to the user can make for a good solution.  In both cases you want to throw in a serverside salt that makes it unlikely someone will figure out your scheme.

Link to comment
Share on other sites

If you're going to store that in their user row, then sure that could work, although I'd highly recommend at least an additional salt or secret phrase that the md5() has be based on -- using the time() alone isn't a very good input, while something like username+phrase+time() is much better. 

 

Just to reiterate, this is only something that should be looked at if the user doesn't already have a valid session.  In other words, you only want to go to the expense of checking the rememberme cookie if they aren't already logged in.  Then check cookie, and if no hash match, prompt for username/pw.

 

Link to comment
Share on other sites

kinda confused so how would i actually code this?

The way i am doing??

 

function rememberME($username, $time){
$_COOKIE['UserSession'] = $username
$config->query("UPDATE `member` SET `cookie` = '".$time."' WHERE `username` = '".$username."'");
setcookie('UserSession', $time, $expires);
}

 

then do $_COOKIE['UserSession'] = $username

??

Link to comment
Share on other sites

The $_COOKIE comes from the webserver, and includes all cookies sent from the client browser.  You never set it -- only read from it.

 

One comment-- I don't know what your user table looks like, but you'd be better off if the key was an integer, and not the the username.  Nevertheless ---

 

function rememberME($username) {
   // Call this function to set cookie on new login, when remember me is checked.
   define('SECRET', 'Some secret phrase you want to use here for your site.');  
   $hash = md5($username . SECRET . time());  
   $config->query("UPDATE member SET remembercode = '$hash' WHERE username = '$username');
   setcookie("sesstoken", $hash, time() + 259200, "/", ".yoursite.com", 1);
}

Link to comment
Share on other sites

The $_COOKIE comes from the webserver, and includes all cookies sent from the client browser.  You never set it -- only read from it.

 

One comment-- I don't know what your user table looks like, but you'd be better off if the key was an integer, and not the the username.  Nevertheless ---

 

function rememberME($username) {
   // Call this function to set cookie on new login, when remember me is checked.
   define('SECRET', 'Some secret phrase you want to use here for your site.');  
   $hash = md5($username . SECRET . time());  
   $config->query("UPDATE member SET remembercode = '$hash' WHERE username = '$username');
   setcookie("sesstoken", $hash, time() + 259200, "/", ".yoursite.com", 1);
}

 

man duhh to me lol (about the integer)

but now when writing the rest of my code how will they stay logged in?

 

and when they logout

 

function logout(){
	if(isset($_COOKIE['sesstoken'])){
		setcookie("sesstoken", "", time() - 3600);
		$config->query("UPDATE `member` SET `remembercode` = '' WHERE `username` = '".$username."'");
	}
	$username = "";
	$password = "";
	$userQ = "";

	session_destroy();
}

 

so lets say your logged in and your at main.php

how do i classify it so it will stay logged in

like instead of doing

if(isset($_SESSION['ID'])){}

 

thats what i usually do (but i am recoding)

 

sorry for being a newb on this haven't coded in 1-2 years and trying to learn OOP and other stuff

Link to comment
Share on other sites

Ok, so if $_SESSION['ID'] is what you are using to indicate the presence of a session, then there's no problem using that.  If ID is an integer (perhaps the user ID?) then your code would be better to have: 

 

if (isset($_SESSION['ID']) && ((int)$_SESSION['ID'] > 0) {
  // logged in
} else {
  header("Location: login.php")
  exit;
}

 

Your logout is looking good.  However, you do want to add

 

session_unset();

 

before your session_destroy.  You might also want to be super careful and specifically unset($_SESSION['ID']) if that's your key variable.  The important thing about this is that session_start() must have been called before any of these calls. 

Link to comment
Share on other sites

This comes into play when you authenticate/login the user. 

 

IF the user doesn't have a $_SESSION['ID'] set, then they are not logged in.

 

  -- If not logged in check the $_COOKIE['sesstoken'] and query the user table where remembercode = $_COOKIE['sesstoken'].  If you get a row back, load that user up just as if they had logged in.

 

-- else

 

-- Display the login form.

 

 

IN the login form, if the remember check box is set,  and the user authenticates, then you call the rememberMe() function.

 

Link to comment
Share on other sites

wait so couldn't i use $_SESION['id'] to check if logged in

and when the $_SESSION expires i can have it check if $_COOKIE['sesscookie'] is set then reset the $_SESSION['id'] right?

 

Yes you should use $_SESSION['ID'] to check if logged in.

 

When a session expires you will not know it.  All that you will know is that the user does not have a $_SESSION['ID'] that is set and > 0.  In that case, you should check the sesstoken cookie to see if they have the remember me setting.  If so, then try and find them by the sesstoken you stored, and if found, load up the info, set the $_SESSION['ID'] and any other pertinent info into the session and and log them in. 

 

Perhaps it would be easiser to just think of rememberme as a key that gets you through the front door into your apartment, without having to give your name and pw. 

Link to comment
Share on other sites

  • 3 weeks later...

I just did

  	if($_POST['remember']){
		$cookie = md5($myusername . SECRET . time()); 
		setcookie("sesstoken", $cookie, time() + 259200, "/", WEBSITE, 1);
		$config->query("UPDATE `members` SET `cookie`='".$cookie."' WHERE `username`='".$myusername."'");
		echo($_COOKIE['sesstoken']);
		die();
	}

 

and i got an error of

 

Notice: Undefined index: sesstoken in C:\wamp\www\clanphobia.net\process.php on line 184

 

Which is the line of "setcookie()"

Link to comment
Share on other sites

There's plenty of ways to do it, but this one makes it very easy:  https://addons.mozilla.org/en-US/firefox/addon/315

 

Install it, will require a restart.  When you're testing the page, right click on it, and choose "View Page Info."  That dialogue will now have a Cookies tab.  Click on that for a list of all the current cookies.

 

You can also use the LiveHTTPHeaders, and Firebug addons in different ways to look at the HTTP Headers, which should have the cookies that are being passed in the HTTP header.

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.