Page 1 of 1

Login script help for access to certain

Posted: Fri May 08, 2009 3:39 am
by benwizzi
I got this script login_system v0.01 which works perfect but being pretty new to PHP i do not know how to modify the files so only certain pages on my website will be password protected. Or is this something i have to setup on mySQL database??

Here's the login.php

Code: Select all

<?php require_once('Connections/modulatemedia.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}
 
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}
 
if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=md5($_POST['password']);
  $MM_fldUserAuthorization = "";
  $MM_redirectLoginSuccess = "admin.php";
  $MM_redirectLoginFailed = "login.php";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_modulatemedia, $modulatemedia);
  
  $LoginRS__query=sprintf("SELECT username, password FROM users WHERE username=%s AND password=%s",
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
   
  $LoginRS = mysql_query($LoginRS__query, $modulatemedia) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
     $loginStrGroup = "";
    
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;       
 
    if (isset($_SESSION['PrevUrl']) && false) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];  
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style2 {font-size: 10px}
.style3 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; }
.style4 {font-family: Verdana, Arial, Helvetica, sans-serif}
.style5 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9px; }
-->
</style>
<script type="text/javascript">
<!--
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->
</script>
 
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
<!--
.style6 {font-size: 9px}
-->
</style>
</head>
 
<body>
<form ACTION="<?php echo $loginFormAction; ?>" id="form1" name="form1" method="POST">
  <label></label>
  <table width="241" border="0" align="center">
    <tr>
      <td colspan="2"><h2 class="style4">Login</h2></td>
    </tr>
    <tr>
      <td width="79"><span class="style3"><strong>
        
      </strong>        
        
      </span>        <span class="style2">
     
      </span>      <div align="right" class="style3"><strong>Username:</strong></div>      </td>
      <td width="152"><input name="username" type="text" id="username" tabindex="1" maxlength="20" /></td>
    </tr>
    <tr>
      <td><span class="style3"><strong>
       
      </strong>        
        
      </span>        <span class="style2">
      
      </span>     <div align="right" class="style3"><strong>Password:</strong></div>      </td>
      <td><input name="password" type="password" id="password" tabindex="2" maxlength="20" /></td>
    </tr>
 
    <tr>
      <td>&nbsp;</td>
      <td><input name="submit" type="submit" id="submit" tabindex="4" onclick="MM_validateForm('username','','R');MM_validateForm('password','','R');MM_validateForm('email','','RisEmail');return document.MM_returnValue" value="Login" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><span class="style4"><a href="register.php" class="style5">register</a><span class="style6"> | <a href="mailto:admin@yoursite.com">forgot passwprd?</a></span></span></td>
    </tr>
  </table>
  
</form>
</body>
</html>
 
admin.php

Code: Select all

<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}
 
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
    
  $logoutGoTo = "login.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";
 
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 
 
  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}
 
$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 9px;
}
-->
</style>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
 
<body>
<p>You are logged in!</p>
<p><span class="style1"><a href="<?php echo $logoutAction ?>">Log out</a></span></p>
</body>
</html>
 
And finally the register.php

Code: Select all

<?php require_once('Connections/modulatemedia.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
 
// *** Redirect if username exists
$MM_flag="MM_insert";
if (isset($_POST[$MM_flag])) {
  $MM_dupKeyRedirect="register.php";
  $loginUsername = $_POST['username'];
  $LoginRS__query = sprintf("SELECT username FROM users WHERE username=%s", GetSQLValueString($loginUsername, "text"));
  mysql_select_db($database_modulatemedia, $modulatemedia);
  $LoginRS=mysql_query($LoginRS__query, $modulatemedia) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
 
  //if there is a row in the database, the username was found - can not add the requested username
  if($loginFoundUser){
    $MM_qsChar = "?";
    //append the username to the redirect page
    if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
    $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
    header ("Location: $MM_dupKeyRedirect");
    exit;
  }
}
 
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO users (username, password, email) VALUES (%s, md5(%s), %s)",
                       GetSQLValueString($_POST['username'], "text"),
                       GetSQLValueString($_POST['password'], "text"),
                       GetSQLValueString($_POST['email'], "text"));
 
  mysql_select_db($database_modulatemedia, $modulatemedia);
  $Result1 = mysql_query($insertSQL, $modulatemedia) or die(mysql_error());
 
  $insertGoTo = "login.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style2 {font-size: 10px}
.style3 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; }
.style4 {font-family: Verdana, Arial, Helvetica, sans-serif}
.style7 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9px; }
-->
</style>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
<!--
function MM_validateForm() { //v4.0
  if (document.getElementById){
    var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
    for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
      if (val) { nm=val.name; if ((val=val.value)!="") {
        if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
        } else if (test!='R') { num = parseFloat(val);
          if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
          if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
            min=test.substring(8,p); max=test.substring(p+1);
            if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
      } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
    } if (errors) alert('The following error(s) occurred:\n'+errors);
    document.MM_returnValue = (errors == '');
} }
//-->
</script>
</head>
 
<body>
<form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>">
  <label></label>
  <table width="241" border="0" align="center">
    <tr>
      <td colspan="2"><h2 class="style4">Registration</h2></td>
    </tr>
    <tr>
      <td width="79"><span class="style3"><strong>
        
      </strong>        
        
      </span>        <span class="style2">
     
      </span>      <div align="right" class="style3"><strong>*Username:</strong></div>      </td>
      <td width="152"><input name="username" type="text" id="username" tabindex="1" maxlength="20" /></td>
    </tr>
    <tr>
      <td><span class="style3"><strong>
       
      </strong>        
        
      </span>        <span class="style2">
      
      </span>     <div align="right" class="style3"><strong>*Password:</strong></div>      </td>
      <td><input name="password" type="password" id="password" tabindex="2" maxlength="20" /></td>
    </tr>
    <tr>
      <td><span class="style3"><strong>
        
      </strong>        
       
      </span>        <span class="style2">
     
      </span>      <div align="right" class="style3"><strong>*Email:</strong></div>      </td>
      <td><input name="email" type="text" id="email" tabindex="3" maxlength="50" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input name="submit" type="submit" id="submit" tabindex="4" onclick="MM_validateForm('username','','R');MM_validateForm('password','','R');MM_validateForm('email','','RisEmail');return document.MM_returnValue" value="Register" /></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><p class="style7"><a href="login.php">login</a></p></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><span class="style7">*required fields</span></td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1" />
</form>
</body>
</html>
 

Re: Login script help for access to certain

Posted: Fri May 08, 2009 4:50 am
by ben.artiss
Hi there,

In my opinion it's a bit naughty to use Dreamweaver's built-in stuff (although it is pretty sturdy!), however at least they moved away from cookies to do a login system!

You could copy and paste lines 1-73 of admin.php and put them above the <!DOCTYPE tag or <html> tag of any page you would like to restrict, but it's a bit messy and hard to manage in this way though, but if you're new to PHP there's one good way to learn: get in there and play!

Read the comments in the files for a bit more info on what's going on. Don't forget though, you could take the functions and put them in a separate file (and include the file when it's needed). Hope that helps a little.

Re: Login script help for access to certain

Posted: Fri May 08, 2009 6:41 am
by benwizzi
Cool I'll try that out...

Here's anoter problem now. I've been trying to change what show when the user is logged to show that users name but i've tried to use the php echo function in every which way possible.

I would assume it would be something like
<? php echo $loginUsername; ?>

Re: Login script help for access to certain

Posted: Fri May 08, 2009 7:43 am
by mickd

Code: Select all

 
$_SESSION['MM_Username'] = $loginUsername;
 
That was from the login script, which assigned the username to a session called MM_Username, so to get the username on another page, you would call that.

Code: Select all

 
echo $_SESSION['MM_Username'];
 
As long as they logged in, and the page they go to has session_start() before you echo the username (like the admin file), it'll work.

Re: Login script help for access to certain

Posted: Fri May 08, 2009 8:19 am
by benwizzi
Thanks Mick!! Now i need to attack the main problem.