Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Remembering Non-Registered Visitors

Rated 3.27 (Ratings: 4) (Add your rating)

Log in to add a comment
(2 comments so far)

Want more?

 
Picture of Martin Tsachev

Martin Tsachev

Member info | Full bio

User since: June 26, 2001

Last login: March 29, 2006

Articles written: 6

You have a couple of forms on your site that require the same user information or a single form that is frequently resubmitted by visitors. You don't have the time to implement user registration and don't want to spend hours or days learning somebody else's code. You are not sure if people will sign-up at all. What you need is to "remember" non-registered visitors.

Why people may not register

  • It takes time even if you only fill in a username and password
  • Many services on the web require lots of information
  • Some sites require additional action to activate your account

What are the benefits of remembering visitors?

  • People may opt to turn it off
  • Can coexist with the same service for registered users
  • Doesn't take much time to implement it
  • Doesn't require a database

And the drawbacks

  • Requires cookies, at least when you want it to be permanent
  • The same browser has to be used every time

What exactly is it?

It is a way to remember the information the visitor of your site entered either for the current session or for a specified amount of time with a cookie.

When the visitor submits the form the reusable information - the information that doesn't change when the same user fills the form another time - is saved. Depending on the implementation, you could offer an option to permanently save the information as a cookie or just to save it for the session.

What is required?

A server-side scripting language such as PHP, ASP, JSP or anything as CGI that will both display the form and process the submitted values.

And some code

The example provides the code in PHP but as said above it can be done in any server-side scripting language or application.

define('COOKIE_REMEMBER', 'remember-me');

session_load_remembered();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    processData();
} else {
    displayForm();
}

Our cookie name is defined with a constant so if you want to change it you can do it in one place. The first function call initializes the session variables from that cookie, if available.

Next we check if we should display the form or process the submitted one.

function session_load_remembered() {
    if (isset($_COOKIE[COOKIE_REMEMBER]) ) {
        // the order of name, email has to be the same as in the code to save the data
        list($_SESSION['name'], $_SESSION['email']) = @unserialize($_COOKIE[COOKIE_REMEMBER]);
    }
}

PHP's unserialize function takes a string representation of a PHP variable - array in our case, and returns the structure itself. We've suppressed error messages with the @ control operator because the cookie may have been modified by the user. The list language construct is used to set the values of our session variables at once.

We've used PHP's 4.1 style superglobal _COOKIE and _SESSION arrays; if you want to use the code with an earlier version of PHP you need to modify the code to HTTP_*_VARS and import it from the global namespace with a global declaration as in the example:

global $HTTP_COOKIE_VARS;

echo $HTTP_COOKIE_VARS[COOKIE_REMEMBER];
function displayForm($subject = '', $comment = '') {
    ?>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']?>"
       >

This isn't perfect HTML: you should add titles to the code, and also wrap the text labels in HTML label elements. Other improvements can also be made, it's up to you.

This is an example PHP function to display a comments form. Note that we've set the default values of the name and email fields to our session variables that will hold the saved data. The other two default values for the subject and comment are just put in case server-side validation fails and we need to redisplay the form with the values filled in.

function processData() {
    // some validation
    // redisplay the form if it fails with a line like:
    // displayForm($_POST['subject'], $_POST['comment']);


    // if all is ok
    $_SESSION['name'] = $_POST['fullName'];
    $_SESSION['email'] = $_POST['email'];

    if (isset($_POST['remember']) ) {
        setcookie(COOKIE_REMEMBER, 
            serialize(array($_SESSION['name'], $_SESSION['email']) ),
            time() + 31104000);
    }

    // add the info to database
}

This one handles the submitted data, validation needs to be put in place of course. When all data is correct we can save our data in the session, and also set up a cookie that will remember the info for the visitor's next visit to the site if he/she requested it.

The POST variable remember will be set to on when the visitor checks the box, otherwise it will not be set at all. The code to set the cookie will make it expire in one year.

If you are on a shared host and your site is accessible under one directory it is recommended to set the next optional parameter to setcookie to that directory to prevent cookie leaks.

Martin Tsachev started using computers in 1992, programming Basic and has since then developed a great passion for them.

Nowadays he runs mtdev - a web site with highlight on PHP.

Serializing Data

Submitted by Lando on June 25, 2002 - 11:01.

Problems with this method
While I agree tracking your none registered users is probably a help, I don't see how serializing the information and sending it back to the user as a cookie helps out that much... Some problems as I see it are
Taint Checking... You have to check that information every time it comes in rather than once if you store it in the database
Cookie Size... How big are to going to make that cookie? Seems to me that since the client has to send it each time they connect to you, your going to slow them a bit if they are on a 28.8K dialup...

What's the purpose of not storing the information in a database... I don't see that it will overload your system and at least you have control of the information.

Basically I would treat non-registered users just like normal users except that they don't have a login. Use a cookie to track their information record and have done with it...

I can see how your are sending the information to the client. However, if you have a lot of information you want to save I doubt cookies are the best means of doing this.

Looking at your example, why send the complete cookie every time, why not just send the information from the form in separate cookies, ie _name _address, etc Rather than serializing in one variable...

Anyway, briefly, here's how I track my users.

Client Arrives:

Client sent cookie?
Yes: Pull cookie get customer tracking number from database lookup of cookie_id
No: Check Get Vars

::Check Get Vars::
Client sent ID through get vars?
Yes: Get customer traching number from database lookup of get variable
No: Check Path Var
:: Check Path Var ::
Client sent ID via path variable?
Yes: Get customer tracking yada yada yada
No: Check Post VAR

::Check Post Var::
Client sent ID through POST vars?
Yes: Get customer tracking yada yada yada
No: Generate New customer ID

::Generate New Customer ID::
Generate Unique 40digit (Alpha-num) id
Send Cookie to brower
Reload Page using header location: add Get Var

The next time through the system if the cookie is not returned and the get var is, that means that I have to track there info with something other than cookies... But I have their user id and I just save the method of tracking in a database as to how I should submit their information to them...

Of course I am using a database to track customer information, but if I store the information in the user's cookie then the user can change that information. Which means that information has to be treated as tainted and I shouldn't display any of that information back to the user without checking it for tainting.

Plus I can store a virtually unlimited amount of information about the user locally without having the client have to push me cookie information each time.

Probably wandered off the subject a bit...

login or register to post comments

Re: Serializing data

Submitted by Martin Tsachev on June 26, 2002 - 10:39.

The problem with checking the data every time is easily solved if you just load the cookie only if the session is not set (although on shared hosts that may be a problem too).

The size is not really an issue unless you have a 100KB name, as far as I can see it is 5 bytes only so discard that too. You don't want to make a file on your visitors' life do you?

The proposed solution with creating user records is nice but you will need some garbage collection, say delete all records for people that haven't revisited the site for a week or something unless you are willing to waste your hdd for useless database entries. You may be able to store virtually unlimited amount of information for a visitor but can you do it for all of them?

And what difference will it make if I send the data in different cookies and not in one - just a waste of cookies as the are a limited resource and the limit for number of cookies is closer than the size limit.

As for taint checking I don't see what's the big problem with displaying data the user submitted only to him/her - you can pass cookies to other people.

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.