Jump to content

Basic Login System for any Website


Archadian28

Recommended Posts

*** REWRITTEN FOR SECURITY PURPOSES ***

 

Ok well i see alot of posts about login systems so i will post mine. This is for an admin and regular member login. If you dont want the admin part I will show you want to remove at the end of the post. You can alter any code to fit your needs. I have removed the name of the cookie in this example i will explain what to change/add at the end of this post and where. I wrote this myself so use it or change it as needed. This will be based on the form redirecting to index.php. This is just basic code:

 

MAKE SURE YOU HAVE session_start(); at the top of the page...

 

Login Form:

 


<div id="login">

   <?php

   if (!isset($_SESSION['usern']) && !isset($_SESSION['sess'])) { // Checks to see if the cookie is set for a logged in member, if not show the form to login

   ?>

       <table border="0" cellspacing="0" cellpadding="0">
       <form name="login" method="POST" action="index.php"> // add the page the form will redirect to on submit to check the data in the form.

       <tr>
       <td><INPUT type="text" id="user" class="user" name="usern" size="20" value="Username"></td> // USERNAME will appear in the textbox to change just add <td>Username: </td> before <td><INPUT and remove value=""
       <td><INPUT type="password" id="pass" class="pass" name="passw" size="20" value="Password"></td>// PASSWORD will appear in the textbox to change just add <td>Password: </td> before <td><INPUT and remove value=""
       <td><INPUT type="submit" name="submit" value="Login"></td>
       </tr>

       </form>
       </table>

<?php

   }
   else {

   	header("Location: index.php");

   }

   ?>
   <p class="clear" />
</div>

 

index.php: (placed at the top of the page.)

 


$db = new Database();
$cookie = new Cookie();
$login = new Login();

login(); // Simple right?

 

functions files included on index.php for login();. My function file:

 


function login() {

if ($_POST['submit'] == "Login") {

	$usern = $_POST['usern'];
	$passw = $_POST['passw'];

	unset($_POST['submit']);
	unset($_POST['usern']);
	unset($_POST['passw']);

	global $login;

	$login->check_login($usern, $passw);

}

// Logout

if (isset($_GET['action']) && isset($_SESSION['user']) && isset($_SESSION['sess'])) {

	if ($_GET['action'] === "logout") {

		unset($_GET['action']);

		global $login;

		$login->logout();

	}

}

}

 

Login.php - My login class

 


<?php

class Login {

public function check_login($chkuser, $chkpass) {

		if (isset($chkuser) && isset($chkpass)) {

			global $db;

			$pw = md5($chkpass);

			$db->query = "SELECT usern, passw, admin, adsess FROM TABLE_NAME WHERE usern='$chkuser' AND passw='$pw'";					
			$result = $db->sql_query($db->query);
			$row = $db->fetch_object($result);

			if ($chkuser == $row->usern && $pw == $row->passw) {

			  global $cookie;

			  $cookie->login_cookie($row->usern, $row->passw);

			  if ($row->admin === '1') {

				  $cookie->admin_cookie($row->usern, $row->passw);

			  }



			  if (isset($_SESSION['admin']) && isset($_SESSION['adchk'])) {

					 header("Location: http://www.YOURSITE.com"); // This will redirect the ADMIN to the homepage of the admin section

			  }
			  else {

					header("Location: index.php");  // Change this to your homepage

			  }

			}
			else {

			?>

               	<script type="text/javascript">

                   	alert('The Username and/or Password did not match. Please try again.');

                   </script>

               <?php

				header("Location: index.php");

			}

		}

		else {

			?>

               	<script type="text/javascript">

                   	alert('The Username and/or Password did not match. Please try again.');

                   </script>

               <?php

		}

}

function logout() {

	global $cookie;

	foreach ($_SESSION as $key => $value) {

		$cookie->kill_cookie($key, $value);

	}

	unset($_SESSION[phpSESSID]);

	header("Location: index.php");

}

} // end class

?>

 

My cookie class (cookie.php):

 


<?php

class Cookie {

function login_cookie($username, $password) {

	if (isset($username) && isset($password)) {

		$rand = md5(rand(10000, 99999999));

                       $_SESSION[$usern] = $username;
                       $_SESSION[$user] = md5($username);
                       $_SESSION[$sess] = $rand;

	}
	else {
	?>	
		<script type="text/javascript">

               alert('The Username and/or Password did not match. Please try again.');

          </script>

        <?php  
	}

}

function admin_cookie($user, $pass) {

	global $db; // My database connection...add yours here

	$db->query = "SELECT usern, passw, name, admin FROM TABLE_NAME WHERE usern='$user' AND passw='$pass'";
	$result = $db->sql_query($db->query);
	$row = $db->fetch_object($result);

	if ($user == $row->usern && $pass == $row->passw && $row->admin == 1) {

		if ($row) {

			$md = md5(rand(100, 10000));

			$db->query = "UPDATE TABLE_NAME SET adsess='$md' WHERE usern = '$row->usern' AND passw = '$row->passw'";
			$result = $db->sql_query($db->query);

			if ($result) {

				$name = $row->name;
				$mdname = md5($name);

				$_SESSION['admin'] = md5($mdname);
				$_SESSION['adchk'] = md5($mdname . $mdname);

			}
			else {

				?>	
					<script type="text/javascript">

                           alert('The Admin Privileges were not set.');

                      </script>

       		 <?php  

			}

		} 
		else {

			?>	
				<script type="text/javascript">

                       alert('The Username and Password could not be checked against the database.');

                  </script>

            <?php  

		}

	}
	else {

		?>	
			<script type="text/javascript">

                   alert('The Username and/or Password did not match (Admin).');

              </script>

        <?php  

	}

}

function kill_cookie($name = "", $value = "") {

	if (isset($name)) {

		global $db;

		$user = $_SESSION['usern'];

		$db->query = "SELECT usern, adsess, admin FROM TABLE_NAME WHERE usern = '$user'";
		$result = $db->sql_query($db->query);
		$row = $db->fetch_object($result);

		if ($row->adsess != 0 && $row->usern == $user && $row->admin == 1) {

			$db->query = "UPDATE TABLE_NAME SET adsess='0' WHERE usern = '$user'";
			$db->sql_query($db->query);

		}

		session_destroy($_SESSION);

	}
	else {

		?>	
		<script type="text/javascript">

               alert('The cookies were not deleted.');

          </script>

        <?php  

	}

}

}

?>

 

I have global $db; everywhere so i will post my db class as well...i use the old fashion connects XD

 

database.php:

 


class Database {

protected $db;
protected $num;
public $result;
var $query;

function __construct() {

	global $host, $user, $pass, $name;

	$this->dbhost = $host;
	$this->dbuser = $user;
	$this->dbpass = $pass;
	$this->dbname = $name;
	$this->db_open();
}

protected function db_open() {

	$this->db = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);

	if (empty($this->db)) {

		error('DATABASE CONNECTION FAILED.', MYSQL_ERROR);

	}
	else {

		return $this->db;

	}

}

public function sql_query($query) {

	if (isset($query)) {

			$result = mysqli_query($this->db, $query) or die("Error: ".mysqli_error($this->db));

			if (!isset($result)) {

				die("Query connection failed: " . mysqli_error($this->db)); // Change this to whatever you want

			}
			else {

				return $result;

			}

	}
	else {

		// Your error message here: "Query was empty".

	}

}

public function fetch_object($obj) {

	return mysqli_fetch_object($obj);

}

public function num_rows($num) {

	return mysqli_num_rows($num);

}

function db_close($db) {

	if (isset($db)) {

		mysqli_close($db);
		unset($db);

	}

}

} // end db class

?>

 

I probably missed something so i will read over this 1000 times to make sure i didn't. As far as the actual database table change TABLE_NAME in EVERY query so its directed to your table. my table consists of this:

 


id
name
usern
passw
admin
adsess

 

so make a users table, name it whatever you want to and replace TABLE_NAME with whatever you name the table and add those rows in the code above so everything will work. You can add more to the users if you want but those 6 rows MUST be included. As far as the admin part of it if you don't need it just leave it in the code. You might be able to use it later. if you do use the admin code just add this to whatever you want ONLY the admins to see, whether its a page or simple paragraph:

 


if (isset($_SESSION['admin']) && isset($_SESSION['adchk'])) {

   // ADMIN EYES ONLY!!!

}

 

And for members only no guests:

 


if (isset($_SESSION['user']) && isset($_SESSION['sess']))

   // NO GUESTS ALLOWED!!!

}

 

For members and admins only no guests just combine both of them.

 

The dababase class i posted has my db info (username, password, etc.) require() thats what the global $host, $user, $pass, $dbname; is for if you want to include that in the database class change this:

 

class Database {

protected $db;
protected $num;
public $result;
var $query;

function __construct() {

	global $host, $user, $pass, $name;

	$this->dbhost = $host;
	$this->dbuser = $user;
	$this->dbpass = $pass;
	$this->dbname = $name;
	$this->db_open();
}

protected function db_open() {

 

To this:

 


class Database {

private $dbhost = "localhost"; // Your mysql server address (web address or IP address)
private $dbuser = "USERNAME";
private $dbpass = "PASSWORD";
private $dbname = "TABLE_NAME"; // your database name 
protected $db;
protected $num;
public $result;
var $query;

function __construct() {

	$this->db_open();

}

protected function db_open() {

 

Well i hope this helps. Again, like the pagination post, im sure this looks very confusing. Just add the login form to your page, copy and paste the code for the index.php in the index.php file (main page or where ever the login form is going once the user clicks submit) then copy and paste the cookie, login and database classes and name the files accordingly to the names of the class (lower case) and as an auto loader that loads every class file in the classes folder (or where ever you store your class files put this on the index.php as well:

 


// autoload classes

spl_autoload_register(null, false);
spl_autoload_extensions('.php');

function classLoader($class) {

	$filename = strtolower($class) . '.php';
	$file = 'YOUR_CLASS_DIRECTORY' . $filename; // CHANGE THIS TO YOUR CLASS DIRECTORY 
	if (!file_exists($file)) {

		die("There is no such file: " . $filename . ".");
		return false;
	}

	include $file;
}

spl_autoload_register('classLoader');

 

If i have missed anything please let me know. Enjoy! Oh and for the logout link its just:

 

?action=logout

 

at the end of your URL link :) ex: www.mysite.com/index.php?action=logout

 

This also sets adsess in the database to a md5() encryption and sets it to 0 on logout...so you can compare/check to that as well for admin verification. I will post a full template system for everyone here in the next 24-48 hours so be on the lookout! Enjoy.

 

My mistake, so the errors don't pop up if you DO NOT want the admin system go to the Login.php class and remove this:

 


if ($row->admin === '1') {

                                         $cookie->admin_cookie($row->usern, $row->passw);

                                 }

                                 if (isset($_SESSION['admin']) && isset($_SESSION['adchk'])) {

                                                header("Location: http://www.YOURSITE.com"); // This will redirect the ADMIN to the homepage of the admin section

                                 }
                                 else {

                                               header("Location: index.php");  // Change this to your homepage

                                 }


 

And the "admin" and "adsess" from the SQL query statements. You can leave the admin_cookie in the Cookie.php class file.

Edited by Archadian
Link to comment
Share on other sites

Quick question regarding this:

 

if (isset($_COOKIE['admin']) && isset($_COOKIE['adchk'])) {

 

// ADMIN EYES ONLY!!!

 

}

So if I, as a non-admin user, steal the cookies from a valid user), it allows me access to admin areas of the site? Unless I am misunderstanding something, using cookies for checking to see if a user is logged in or not is terribly unsafe.

 

What also happens to the "adsess" row in the database if the user doesn't log out, and simply closes his browser? Won't he technically be logged out, but the database will still indicate he is logged in?

 

I'm not meaning to be malicious here, just asking questions about the system, since I think security is pretty important. ;)

Link to comment
Share on other sites

Ben is absolutely right. $_SESSION is better because its stored on the server rather than $_COOKIE being stored on the user's computer. I have rewritten the login template with $_SESSION so its more secure. You can go through the files and change usern, user, sess, admin, adchk if you want to but since its $_SESSION and not cookies im not sure you have to :). Any problems or questions let me know.

Edited by Archadian
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...