Sunday, November 25, 2007

Login system (PHP)

Well this seems to be a popular intrest for newbie coders, and some experienced ones, so i'd figure i would post a tutorial for a php / mysql login system. This login system's password will be md5 encoded. You will have to make the script that adds the users yourself. Im just gonna post the login part today.

Step 1:
We will need to create a table for our login system, lets call this table users.
Here is the mysql query to create our table.


CREATE TABLE `users` (
`id` tinyint(4) NOT NULL auto_increment,
`user` text NOT NULL,
`pass` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
);


Step 2:
Lets make the file that will connect to our mysql server and select our database.


mysql_connect("localhost", "db_user", "dbpass") or die("Could not connect to MySQL server!");
mysql_select_db("db_name") or die("Could not find MySQL database");
?>


Lets save this file as connect.php

Step 3:
Lets make the file that actualy protects the pages.


$user = $_COOKIE['user']; //gets the user from the cookies
$pass = $_COOKIE['pass']; //gets the pass from cookies
include("connect.php"); // connects to our database
$login = mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `pass` = '$pass`"); //selects info from our table if the row has the same user and pass that our cookies do
if(!mysql_num_rows($login)) //if the username and pass are wrong
{
header("Location: login.php"); //redirects to our login page
die(); //stops the page from going any further
}
?>


lets call this page protect.php

Step 4:
The Login Form/Processing page.


$act = $_GET['act']; //retrives the page action
if(empty($act)) //if there is no action
{
echo('

Username


Password





');
}
elseif($act == "auth") //if our page action = auth
{
$user = $_POST['user']; //pulls the username from the form
$pw = $_POST['pass']; //pulls the pass from the form
$pass = md5($pw); //makes our password an md5
include("connect.php"); //connects to our mysql database
$login = mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `pass` = '$pass`"); //selects info from our table if the row has the same user and pass that our form does
if(!mysql_num_rows($login)) //if the username and pass are wrong
{
header("Location: login.php"); //redirects to our login page
die(); //stops the page from going any further
}
else
{
setcookie("user", $user, time()+3600);//sets our user cookie
setcookie("pass", $pass, time()+3600);//sets our pass cookie
header("Location: yourpage.php");//instead of yourpage.php it would be your protected page
}
}
?>


Lastly
To protect a page add this to the very first line.


No comments: