HomePHP Page 3 - Developing a User Personalization System with PHP and Cookies
User Login - PHP
Making your site more appealing to repeat traffic is always a priority among web developers. However users of your site are likely to be coming to your site for different reasons. This tutorial will teach you how to use PHP and cookies to make your site more user-customizable and therefore more likely to attract repeat users.
Now a form should be built to enter information, make choices, and then enter the data in the database. Here's a simple form with a few more choices available:
The action in the form is "newuser.php3." Once data has been entered in the form, this script inserts a new row of data in the database.
<? SetCookie("visitor",$login,time()+864000); ?>
<HTML>
<HEAD><TITLE>Thanks!</TITLE></HEAD>
<BODY>
<?
mysql_connect("localhost", "username", "pass") or DIE("Unable to
connect to database");
@mysql_select_db("project") or die("Unable to select database");
$result = mysql_query("Select * from users where login='$login'");
if(!mysql_numrows($result)) {
#Make a new login - entire page follows
$result = mysql_query("insert into users values (
'$login',
'$password',
NOW(),
'$news1',
'$news2',
'$news3')");
?>
<br>
Thanks for logging in!<br><br>
To see what the page looks like with your personal
settings, please <a href="index.php3">return</a>.
<? }
else {
echo "Whoa! Someone has already picked that username!<br><br>";
echo "Please hit the back button and pick a unique login.";
} ?>
</body>
</html>
Notice that "Setcookie" command? We'll talk about on the next page. For now, notice how the database is checked for duplicate logins first (lines 10), then a new row is created (line 12). Afterwards, a link to the start page is given.
At the end of the script, the user gets some feedback if his login is not unique.
Normally to pass variables to any sort of script, variables have to be added to the end of the URL, but what we want is a simple solution, so whenever a user comes to the page, their preferences will be displayed without any mumbo jumbo at the end of the url. We still need a way to pass our scripts information about the user. The best way to do so is with cookies, and nothing handles cookies as easily as PHP3.