FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


PHP Login-Script (With Sessions)





asdfowkw

@ This is a 100% complete, working login system that is free to use for all of you. @


I will keep adding information to this thread and try to help you out with possible problems.



Mysql database info:
Code:
CREATE TABLE members (
  id int(11) NOT NULL auto_increment,
  user varchar(30) NOT NULL default '',
  pass varchar(32) NOT NULL default '',
  name varchar(50) NOT NULL default '',
  email varchar(50) NOT NULL default '',
  PRIMARY KEY  (id)
) TYPE=MyISAM;


conn.php - Database connection information
Code:
<?php
 
// Byt ut mot dina inloggningsuppgifter och databas
$mysql_server = "MYSQL HOST (if on your own computer its here the "localhost" is";
$mysql_user = "MYSQL USERNAME";
$mysql_password = "MYSQL PASSWORD";
$mysql_database = "DATABASE NAME";
 
$conn = mysql_connect($mysql_server, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $conn);
 
 
//A function to use when magic_quotes_gpc isnt set. To prevent SQL-injections, or in better case MySQl-problems.
function db_escape ($post)
{
   if (is_string($post)) {
     if (get_magic_quotes_gpc()) {
        $post = stripslashes($post);
     }
     return mysql_real_escape_string($post);
   }
   
   foreach ($post as $key => $val) {
      $post[$key] = db_escape($val);
   }
   
   return $post;
}
 
 
/*
   Make sure that there's no space's or blank lines after the closing php-tag "?>"
*/
?>


index.php

Code:
<?php
session_start(); // ALWAYS most top of the website
 
include "conn.php"; // The Databaseconnection
 
// Login
if (isset($_POST['submit'])){
 
  $_POST = db_escape($_POST);
 
  $sql = "SELECT id FROM members
         WHERE user='{$_POST['user']}'
         AND pass='{$_POST['passwd']}'";
  $result = mysql_query($sql);
 
  // If username and password wasnt found
  // send to form with error message
  if (mysql_num_rows($result) == 0){
    header("Location: index.php?badlogin=");
    exit;
  }
 
  // Set session with unique index
  $_SESSION['sess_id'] = mysql_result($result, 0, 'id');
  $_SESSION['sess_user'] = $_POST['user'];
  header("Location: welcome.php");
  exit;
}
 
// Logout
if (isset($_GET['logout'])){
  session_unset();
  session_destroy();
  header("Location: index.php");
  exit;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type"
  content="text/html; charset=iso-8859-1">
<title>Index</title>
</head>
<body>
<?php
 
// If not logged in show form, else logout link
if (!isset($_SESSION['sess_user'])){
 
  echo "<h3>Log in</h3>\n";
 
  // Show error message at bad login
  if (isset($_GET['badlogin'])){
    echo "Wrong username or password!<br>\n";
    echo "Try again!\n";
  }
 
?>
<form action="index.php" method="post">
Username:<br>
<input type="text" name="user"><br>
Password:<br>
<input type="password" name="passwd"><br>
<input type="submit" name="submit" value="Log in">
</form>
Not a member yet?<br>
<a href="register.php">Registeer</a>
<?php
 
} else {
 
  echo "<a href=\"index.php?logout=\">Log out</a>\n";
 
}
 
?>
</body>
</html>


register.php - to submit a registration

Code:
<?php
session_start();
 
include "conn.php";
 
if (isset($_POST['submit'])){
 
  $_POST = db_escape($_POST);
 
  // Remove possible spaces in beginning or at the end
  foreach($_POST as $key => $val){
    $_POST[$key] = trim($val);
  }
 
  // Check for empty fields
  if (empty($_POST['user']) || empty($_POST['passwd']) ||
      empty($_POST['name']) || empty($_POST['email'])) {
    $reg_error[] = 0;
  }
 
  // Check if the username is avaible
  $sql = "SELECT COUNT(*) FROM members WHERE user='{$_POST['user']}'";
  $result = mysql_query($sql);
  if (mysql_result($result, 0) > 0) {
    $reg_error[] = 1;
  }
 
  // Check if email seems to be okay
  if (!preg_match('/^[-A-Za-z0-9_.]+[@][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)*[.][A-Za-z]{2,6}$/', $_POST['email'])) {
    $reg_error[] = 2;   
  }
 
  // Check so the passwords match
  if ($_POST['passwd'] != $_POST['passwd2']) {
    $reg_error[] = 3;
  }
 
  //No errors? Save info and login and redirect to welcome.php
  if (!isset($reg_error)) {
    $sql = "INSERT INTO members(user, pass, name, email)
            VALUES('{$_POST['user']}', '{$_POST['passwd']}', '{$_POST['name']}', '{$_POST['email']}')";
    mysql_query($sql);
   
    $_SESSION['sess_id'] = mysql_insert_id();
    $_SESSION['sess_user'] = $_POST['user'];
    header("Location: welcome.php");
    exit;     
 
  }
 
} else {
 
  // Set variables for empty form
  for ($i=0; $i<4; $i++) {
    $back[$i] = "";
  }
 
}
 
$error_list[0] = "All fields isn't filled out";
$error_list[1] = "The username is already taken";
$error_list[2] = "Bad email";
$error_list[3] = "The passwords dosn't match";
 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type"
  content="text/html; charset=iso-8859-1">
<title>Register</title>
</head>
<body>
<h3>Register</h3>
<?php
if (isset($reg_error)){
 
  echo "Something went wrong:<br>\n";
  echo "<ul>\n";
  for ($i=0; $i<sizeof($reg_error); $i++) {
    echo "<li>{$error_list[$reg_error[$i]]}</li>\n";
  }
  echo "</ul>\n";
 
  $back[0] = stripslashes($_POST['user']);
  $back[2] = stripslashes($_POST['name']);
  $back[3] = stripslashes($_POST['email']);
 
}
?>
<form action="register.php" method="post">
<table cellspacing="3">
 
<tr>
<td>Username:</td>
<td><input type="text" name="user" value="<?php echo $back[0]; ?>"></td>
</tr>
 
<tr>
<td>Password:</td>
<td><input type="password" name="passwd" value=""></td>
</tr>
 
<tr>
<td>Repeat password:</td>
<td><input type="password" name="passwd2" value=""></td>
</tr>
 
<tr>
<td>Your name:</td>
<td><input type="text" name="name" value="<?php echo $back[2]; ?>"></td>
</tr>
 
<tr>
<td>E-mail</td>
<td><input type="text" name="email" value="<?php echo $back[3]; ?>"></td>
</tr>
 
<tr>
<td colspan="2" align="center">
  <input type="submit" name="submit" value="Save your information">
</td>
</tr>
 
</table>
</form>
 
</body>
</html>


welcome.php - The page you are redirected to after a successfull login

Code:
<?php
session_start();
 
// Check if logged in = session is set
if (!isset($_SESSION['sess_user'])){
  header("Location: index.php");
  exit;
}
 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type"
  content="text/html; charset=iso-8859-1">
<title>Welcome</title>
</head>
<body>
 
Welcome <?php echo $_SESSION['sess_user']; ?><br>
<a href="index.php?logout=">Logga ut</a>
 
</body>
</html>


Relative Threads:
Login System (PHP)
silverdown
Thanks for sharing..
Related topics
PHP login script problem
Simple PHP Login Script
150 frih$ if you make me a login script with....
Free PHP/MySQL login script
Free php script login / register , GREAT!
PHP login/logout problem
Php voting script needed (URGENT)
Login Script - PHP
Fix up a login script
Frih$ on offer for PHP Login System
Hot or Not PHP-Nuke script
What's the best PHP Wiki script?
php login module
simple login script
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.