Jump to content

Recommended Posts

Hey people,
Ive been using sessions for my news site,
But i wish to add a remember me feature for my members.
In my sessions i have a session[user] with an array of database user info.
Is there any way to do this with cookies or will i have to set a new cookie for each array value?

-Andy
Link to comment
https://forums.phpfreaks.com/topic/32182-cookies/
Share on other sites

While you cant store arrays in a cookie, it expects a string and will give you an error if you don't provide it something it can use as one, you can serialize() the array and unserialize() it later... take this example...

[code=php:0]
$testArray = array('foo' => 'bar', 'stuff', 'thing' => 'morestuff');
setcookie('stuff', serialize($testArray));
[/code]

you could then on the next page...

[code=php:0]
$testArray = unserialize($_COOKIE['stuff']);
[/code]

and $testArray contains what it did originally.... it should work... but remember you're limited to about 4k in a cookie, so you might not want HUGE arrays being stuffed into the cookie.

The main problem with doing this is that if the passwords are stored in plain text that can easily be picked out. I'd suggest at least storing them in md5 on the clients cookie, though there are better things you could do for security.
Link to comment
https://forums.phpfreaks.com/topic/32182-cookies/#findComment-149371
Share on other sites

Yeah here is the code.. its a function because i use it all around the site...

[code]
<?php
function displaylogin(){
$formaction = $_SERVER['PHP_SELF'];
$loginform = "
<form action=$formaction method=post name=loginform>
Username:
<br>
<input type=text name=username size=20 class=field1>
<br>
Password:
<br>
<input type=password name=password size=20 class=field1>
<br><br>
<input type=submit value=login class=button1 name=login>
<br><br>
<a href=register.php>Click Here To Register</a>
</form>
";
if (!$_SESSION['user'] && !$_POST['login']){ // No session + No Form Login... Display the form...
echo $loginform;
} elseif ($_POST['username']){ //if the form has been submitted... The ifs + elses between this and next comment arnt that important just checking if the login details are correct...

$username = $_POST['username'];
$password = $_POST['password'];
$password = md5($password);
//---
$result = mysql_query("SELECT * FROM sf_users WHERE username='$username'") or die(mysql_error());
$user = mysql_fetch_array( $result );
if ($user['member_id'] == ""){
echo "<font color=\"#FF0000\"><b>Unknown username, please try again</b></font>";
echo $loginform;

} else {
$dbusername = $user['username'];
$dbpassword = $user['password'];
if ($username == $dbusername && $password == $dbpassword){
session_register("user");
$result = mysql_query("SELECT * FROM sf_users WHERE username='$username'") or die(mysql_error());
$_SESSION['user'] = mysql_fetch_array($result);
$uname = $_SESSION['user']['username'];
$member_id = $_SESSION['user']['member_id'];
$datestamp = DATESTAMP;
$newip = $_SERVER['REMOTE_ADDR'];
echo "<br><font color=white><i>Loading... Please wait...</i></font><br>";
mysql_query("UPDATE sf_users SET `last_login` = '$datestamp' WHERE `sf_users`.`member_id` =$member_id");
if ($_SESSION['user']['cus_ip'] == "0"){
mysql_query("UPDATE sf_users SET `ipaddress` = '$newip' WHERE `sf_users`.`member_id` =$member_id");
}
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"0; URL=members.php\">";
} else if ($username == $dbusername && $password != $dbpassword){
echo "<font color=\"#FF0000\"><b>Your Password is incorrect</b></font>";
echo $loginform;

} else {
echo "<font color=\"#FF0000\"><b>Unknown System Error!<br> Please ensure your Cases are correct!</b></font>";
}
};


} elseif ($_SESSION['user']){
//If we have the session... echo the username has logged in
//Display member options...

$uname = $_SESSION['user']['username'];
$urank = $_SESSION['user']['rank'];
$uid = $_SESSION['user']['member_id'];
if($_SESSION['user']['active'] != "1"){
echo "<font color='#FFFFFF'><i>You have not yet activated your account! Please activate your account via the email sent to you. For security we can not resend the email. If this is a problem, please contact an admin.</i></font><br><br>";
};
echo "<font color='#FFFFFF'><b>Welcome Back,<br>$urank $uname</b></font><br>";
echo "<br>";
echo "<a href='members.php'>[Members Area]</a><br>";
echo "<a href='forums'>[Forums]</a><br>";

  if ($_SESSION['user']['CL'] >= 2){
  echo "<a href='admin/'>[Admin Panel]</a><br>";
  }

echo "<a href='logout.php'>[Logout]</a><br>";

}
};
?>
[/code]

Thanks
-Andy
Link to comment
https://forums.phpfreaks.com/topic/32182-cookies/#findComment-149389
Share on other sites

I have modified your code a little, mainly due to repeating yourself and doing a lot of unneeded checks. Here is your new code:
[code]<?php

function displaylogin()
{
    $formaction = $_SERVER['PHP_SELF'];

    $loginform = <<<HTML
<form action="{$formaction}" method="pos"t name="loginform">
Username:
<br />
<input type="text" name="username" size="20" class="field1">
<br />
Password:
<br />
<input type="password" name="password" size="20" class="field1">
<br /><br />
<input type="submit" value="login" class="button1" name="login">
<br /><br />
<a href="register.php">Click Here To Register</a>
</form>
HTML;

    if(!isset($_SESSION['user']) && !isset($_POST['login']))
    {
        // No session + No Form Login... Display the form...
        echo $loginform;
    }
    elseif (isset($_POST['username']))
    {
        // if the form has been submitted... The ifs + elses between this and next comment arnt
        // that important just checking if the login details are correct...

        $username = mysql_real_escape_string($_POST['username']);
        $password = md5($_POST['password']);

        $sql = "SELECT * FROM sf_users WHERE username='$username' AND `password`='$password'";

    $result = mysql_query($sql) or die(mysql_error());

        if(mysql_num_rows($result) == 1)
        {
            $user = mysql_fetch_array($result);

    $_SESSION['user'] = $user;

    $member_id = $_SESSION['user']['member_id'];
    $datestamp = DATESTAMP;
    $newip = $_SERVER['REMOTE_ADDR'];

            /* Preparing the cookie data:
            ** We arew going to store it in an array
            ** then when we save it to cookie
            ** we will serialize it */
            $cookieDATA[] = $member_id;
            $cookieDATA[] = $username;
            $cookieDATA[] = $password;

            /* set the remeberMe cookie, it should last around 1 month.
            ** This can be changed by changing 2678400 to however long
            ** in secounds you want the cookie to last */
            setcookie('rememberMe', serialize($cookieDATA), time()+2678400);

            $sql = "UPDATE sf_users SET `last_login` = '$datestamp' WHERE `sf_users`.`member_id` =$member_id";

    $result = mysql_query($sql);

            echo "<br><font color=white><i>Loading... Please wait...</i></font><br>";

            if ($_SESSION['user']['cus_ip'] == "0")
            {
                mysql_query("UPDATE sf_users SET `ipaddress` = '$newip' WHERE `sf_users`.`member_id` =$member_id");
            }

    echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"0; URL=members.php\">";
        }
        else
        {
            echo "<font color=\"#FF0000\"><b>Username and/or password are incorrect. Please try again</b></font>" . $loginform;
        }
    }
    elseif (isset($_SESSION['user']))
    {
        //If we have the session... echo the username has logged in
        //Display member options...

        $uname = $_SESSION['user']['username'];
        $urank = $_SESSION['user']['rank'];
        $uid = $_SESSION['user']['member_id'];

        if($_SESSION['user']['active'] != "1")
        {
            echo <<<HTML
    <font color='#FFFFFF'><i>
      You have not yet activated your account! Please activate your account via the email sent to you. For security we can not
      resend the email. If this is a problem, please contact an admin.</i>
    </font><br />
    <br />
HTML;
        }

        echo <<<HTML
    <font color="#FFFFFF"><b>Welcome Back,<br>{$urank} {$uname}</b></font><br />
    <br />
    <a href="members.php">[Members Area]</a><br />
    <a href="forums">[Forums]</a><br />

HTML;

        if ($_SESSION['user']['CL'] >= 2)
        {
        echo '<a href="admin/">[Admin Panel]</a><br />';
    }

        echo '<a href="logout.php">[Logout]</a><br />';
    }
}

?>[/code]
The cookie that should be setup is called [b]remeberMe[/b]. When you grab the cookie using [code=php:0]$_COOKIE['remeberMe'][/code] you will need to [url=http://php.net/unserialize]unserialize[/url] it. As the cookie holds an array of 3 items which are member id, username and password.

NOTE: You may get errors. This code is untested however I checked over it for any errors. If you get any errors post theme here and I will have a look. If you get no errors then that will be a bonus. But it shouldn't.

The only thing you need to do is create the bit where it fetches the cookie and signs the person in automatically which you should be able to do.
Link to comment
https://forums.phpfreaks.com/topic/32182-cookies/#findComment-149402
Share on other sites

[quote]
Warning: Cannot modify header information - headers already sent by (output started at /home/shadowfl/public_html/inc/header.inc.php:78) in /home/shadowfl/public_html/common.php on line 99

[/quote]

Thats the error. and i am calling the function within my pages table.. you can see it at www.shadowfleet.info
Link to comment
https://forums.phpfreaks.com/topic/32182-cookies/#findComment-149437
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.