?
Solved

login script with MySql

Posted on 2003-03-06
23
Medium Priority
?
323 Views
Last Modified: 2008-02-01
what i need is a script that will allow users to login.

it needs to have a feature that i can put a line of code on a "Members Only" page and it will redirect the users to a login page.  it also needs to have a feature to allow users to sign up.

please help me, i have been looking for one for about 1 month now and i havent found any good ones.  

thank you,
Matt :-)
0
Comment
Question by:mattjp88
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
  • 6
  • +1
23 Comments
 
LVL 15

Expert Comment

by:VGR
ID: 8083490
do it yourself :D
basically, it's a page who by default displays a FORM "please login" with login and password TEXT fields.
Then on the press to "enter" button, the same page reacts by comparing in the DB the login/pwd entered.
Then grants access by setting a session value and redirects to "members only" page.
If login failed, displays "login failed", logs the missed attempt and stays put on the HTTP FORM.

The "members only" page check for the session variable and redirects to the login page is missing, else works normally

Pretty standard.

Do you want to see some code ?
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8083650
yeah. i dont know how to compare the names with the database.  i only need something simple.  nothing super complicated.  can you also show me how to let the users sign up by them selves, that way i dont have to put in new users everytime someone wants a login name.

thank you :-)
0
 
LVL 15

Accepted Solution

by:
VGR earned 160 total points
ID: 8084224
main page (the one protected by login)
<?
session_start();
require 'session.inc.php';

//
// ----------------------------- AUTH -----------------------------------
//
if ($sess_pseudo=='visitor') {
  if (!isset($auth)) {
  echo "<HTML><HEAD><TITLE>Protected Area</TITLE></HEAD><BODY>";
  echo "Enter login and password\n";
  echo "<table border=0 cellpadding=0 cellspacing=0 width=\"100%\">";
  echo "<tr><td bgcolor=#333399 align=center><font color=#FFFFFF size=2 face=Arial>";
?>
<FORM METHOD="POST" ACTION=<?echo $PHP_SELF;?>>
pseudonym <INPUT border=0 TYPE=text NAME=locPseu VALUE="" SIZE=20 MAXLENGTH=48>&nbsp;&nbsp;
password <INPUT border=0 TYPE=password NAME=locPW VALUE="" SIZE=8 MAXLENGTH=8>&nbsp;&nbsp;
<INPUT border=0 TYPE=submit NAME="auth" VALUE="Enter">
</FORM>
<BR>
<?
  echo "</td></tr></table>";
  echo "</td>";
  // finalement bas de page
  echo <<<EOS
      </tr>
    </table>
</body>
</html>
EOS;
  exit;
  } // else on passe ` la suite
}

//else begin
// verify user does exist
$linkID=mysql_connect("$dbHost","$dbLogin","$dbPassword") or die ("bad connect".mysql_error());
mysql_select_db($dbName,$linkID) or die ("bad select DB ".mysql_error());
$query="select * from $dbTableUsers where pseudo='$locPseu'";
$result=mysql_query($query,$linkID) or die ("bad query gest user 1 ".mysql_error());
if($res=mysql_fetch_array($result)) {
  // if yes, check password of user
  $locPseu=$res["pseudo"];
  $locID=$res["id"];
  LogAction($locPseu,$REMOTE_ADDR,"attempts entering.",6);
  $locExiste=1;
  $query="select * from $dbTableUsers where pseudo='$locPseu' AND password='$locPW'";
  $result=mysql_query($query,$linkID) or die ("bad query CC user 2 ".mysql_error());
  if($res=mysql_fetch_array($result)) {
    //         si oui, virification si admin
    LogAction($locPseu,$REMOTE_ADDR,"validated entry.",6);
    // infos sessions
    $sess_pseudo=$locPseu;
    $sess_admin=$res["admin"];
    session_register("sess_pseudo");
    session_register("sess_admin"); // toujours, ici
    //
  } else { // password invalide
    //         si non, rejet
    LogAction($locPseu,$REMOTE_ADDR,"entered a bad password.",4);
    echo "Bad password...<BR>";
    exit; // sort du script
  } // if user/pw existe
} else {
  // else show a form to enter as a new user
    LogAction($locPseu,$REMOTE_ADDR,"utilisateur '$locPseu' inexistant.",4);
    echo "Unknown user...<BR>";
    exit; // sort du script
} // if user exists

if ($locExiste==1) { // standard page
echo <<<EOS
<HTML><HEAD><TITLE>
[snip the rest of HTML generation for your page]
EOS;
} else { // formulaire to enter a new account
echo <<<EOS
<font color=red>New user request form</FONT>
<FORM METHOD="POST" ACTION="$SCRIPT_NAME">
pseudonym desired (48c)<INPUT border=0 TYPE=text NAME="FPseu" VALUE="$locPseu" SIZE=20 MAXLENGTH=48><BR>
initial password desired (8c)<INPUT border=0 NAME="FPW" TYPE=text VALUE="$locPW" SIZE=8 MAXLENGTH=8><BR>
email address (35c) <INPUT border=0 NAME="FEmail" TYPE=text VALUE="" SIZE=20 MAXLENGTH=35><BR>
<input type=hidden name=action value="new user request" >
<input type=hidden name=FboolAdmin value=0>
<input type=hidden name=auth value=1>
<input type=hidden name=locPseu value="$locPseu">
<input type=hidden name=locID value=\"$locID\">
<input type=hidden name=locPW value="$locPW">
<input type=hidden name=locAdmin value="$locAdmin">
<input type=hidden name=locExiste value="$locExiste">
<INPUT border=0 name=new TYPE=submit VALUE="Send">
</FORM>
<BR>
EOS;
} // else

?>


now session.inc.php :
<?
//VGR30012003 Criation (Familles) ` partir de BDniouzes
//VGR13022003 ADDed gestion des noeuds et droits d'acchs
//

session_start();

require_once 'typdef.inc.php';
require_once 'dbvarious.inc.php';

if (!isset($sess_admin)) {
      $sess_admin=0;
      session_register("sess_admin");
}

if (!isset($sess_pseudo)) {
      $sess_pseudo="visitor";
      session_register("sess_pseudo");
      $sess_identif="0";
      session_register("sess_identif");
}

if (!isset($sess_identif)) { // difaut en mode ouvert
      $sess_identif="0";
      session_register("sess_identif");
      $sess_certif="0";
      session_register("sess_certif");
}

if (!isset($sess_certif)) { // en thiorie impossible
      LogGAction($sess_pseudo,$REMOTE_ADDR,"pose problhme pour sess_certif.",2);
      $sess_certif="0";
}
session_register("sess_admin");
session_register("sess_noeud");
session_register("sess_pseudo");
session_register("sess_certif");
session_register("sess_ip");
session_register("sess_email");
session_register("sess_status");

?>

now what you need in dbvarious.inc.php and typedef.inc.php :
<?
// dbvarious.inc(lude)
//VGR30092002 Criation (JForum)
// [snip history section]
//
// ----------------------------- ACTIVITE --------------------------------
//
//VGR19032001 MODified this (add criticity parameter 'niveau')
function LogAction($pseudo,$ip,$msg,$level) {
  GLOBAL $dbHost, $dbName, $dbLogin, $dbPassword, $sess_osWin;
  //$msg=date("j-n-Y G:i:s"). $msg; inutile grbce au timestamp (mais moins "joli" ;-) // on ajoute le marquage horaire
  // protections
  $msg=AddSlashes($msg);
  $pseudo=AddSlashes($pseudo);
  if ($sess_osWin==1) $linkID=mysql_connect("$dbHost","$dbLogin","$dbPassword") or die ("bad connect".mysql_error());
   else $linkID=mysql_pconnect("$dbHost","$dbLogin","$dbPassword") or die ("bad connect".mysql_error());
  mysql_select_db($dbName,$linkID) or die ("bad select DB LA ".mysql_error());
  $query="insert into activite (ip,pseudo,action,heure,niveau) values (\"$ip\",\"$pseudo\",\"$msg\",now(),$level)"; // id est en autoincrimentation
//test
//echo "requjte = $query";
//
  $result=mysql_query($query,$linkID) or die ("bad query add activiti ".mysql_error());
} // LogAction Procedure

?>

typedef.inc.php :
<?
session_start();
// difinitions client
// positionne sess_isNS (Boolean)
$ua=getenv("HTTP_USER_AGENT");
$pos=strpos($ua,'(');
$apres='';
if ($pos>0) { $avant=substr($ua,0,$pos); $apres=substr($ua,$pos+1); if (strpos($apres,')')>0) $apres=substr($apres,0,strpos($apres,')')); }
 else $avant=$ua;
$notNS=(strpos($avant,'Mozilla')===false);
if (!$notNS) $notNS=!(strpos($apres,'MSIE')===false);
$sess_isNS=(!$notNS);
session_register("sess_isNS");

// bases de donnies
$dbHost = "localhost"; // or your own hostname
$dbName = "xxyourdbnamexx";
$dbTableUsers = "users";
$dbLogin = "root"; // this is NOT the unix "root" user !
$dbPassword = "xxxx"; // ditto on this
$dbTableStatus = "status";
$dbTableActivite = "activite";
?>


0
WordPress Tutorial 1: Installation & Setup

WordPress is a very popular option for running your web site and can be used to get your content online quickly for the world to see. This guide will walk you through installing the WordPress server software and the initial setup process.

 
LVL 6

Author Comment

by:mattjp88
ID: 8084284
ok. where do i put in my MySql stuff?  
0
 
LVL 15

Expert Comment

by:VGR
ID: 8084323
in this placeholder :
if ($locExiste==1) { // standard page
echo <<<EOS
<HTML><HEAD><TITLE>
[snip the rest of HTML generation for your page]
EOS;
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8084342
no.  my MySql password, username, and database name.  also how many cells does this require,  so i can make the datadase.
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8084355
are all the comments in another language?  i just realized i cant read them. lol
0
 
LVL 15

Expert Comment

by:VGR
ID: 8084561
no, I translated many comments, the principal ones. The rest should not bother you. It's "easy" PHP, after all.

I don't guarantee that those extracts of code, even carefully presented by me, will function from the first try for you once adapted to your needs ;-)

The DB settings are, as I wrote, in the typedef.inc.php file : I even put some "xxx" to clearly show where you had to put your DB name, login and password (usually root/something)
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8084615
Fatal error: Call to undefined function: loggaction()

i looked in all of the files and i cant find that function.  how do i get rid of this error?
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8084691
ok i got that working.
what do i have to do for the MySql database.  i have to make a table in it but how many feilds do i need and what names should i call them.  as you can tell im a newbie.  i have no idea how to use PHP or use a MySql database.
0
 

Expert Comment

by:EViLWolf
ID: 8085209
for the connection...

<?
session_start();
$sessid=session_id();
session_register(); /*This line is optional but is useful when you have multiple pages, instead of only one including others*/

$sql_host = "localhost";
$sql_username = "user";
$sql_password = "pass";
$dbname = "database";

$db_con = mysql_connect($sql_host, $sql_username, $sql_password);
$db_select = mysql_select_db($dbname);
?>


useful queries...

<?
mysql_query("INSERT INTO table(field1, field2, field3, field4) VALUES('value1', 'value2', 'value3', 'value4')"); /*Inserts a new entry to a table (you don't have to put every field, only those you want to add)*/

mysql_query("UPDATE table SET field='value' WHERE field='value'"); /*Updates a value (the WHERE must be there)*/

mysql_query("TRUNCATE table"); /*Empties a table*/

mysql_query("DROP TABLE table"); /*Deletes a table*/

mysql_query("CREATE TABLE 'table'('id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 'field2' TEXT NOT NULL)"); /*This will create a new table, where 'id' will be very useful and will identify every entry with a unique number (doesn't need to be entered when you insert a new entry)*/

$result = mysql_query("SELECT * FROM table ORDER BY field DESC LIMIT 0,10"); /*LIMIT 0,10 means no horizontal limit, 10 vertical -- ORDER BY field DESC and LIMIT are optional (there is also ASC for the order)*/
$nor = @mysql_num_rows($result); /*Get the total number of entries to what you specified*/
for ($i = 0; $i < $nor; $i++) /*Set a loop so it can read every entry 1 by 1*/
{
$record = @mysql_fetch_row($result);
$field1 = $record[0]; /*This is your 1st field*/
$field2 = $record[1]; /*This is your 2nd field, and so on*/
}

mysql_query("DELETE FROM table WHERE field='value'"); /*This deletes an entry*/
?>


useful variables...

<?
$ip = $_SERVER['REMOTE_ADDR']; /*Sets the IP of the visitor in a variable*/

$date = date("Y-m-d"); /*Sets the date in a format of yyyy-mm-dd*/

$Time = date("h:i.s A"); /*Sets the time in a format of h:mm.ss AM/PM*/

$something = $_REQUEST['var']; /*Change var to whatever you want, but when you get something like... index.php?page=main well $_REQUEST['page'] will get it (set the var requested to the one in the URL)*/

$whatever = $_POST['var']; /*This ($_POST['var']) gets anythign that is posted*/

$what = $_SESSION['var']; /*This is anything that is set to a session, you set it using... $_SESSION['var'] = "value"; and this is kept with the user until the session, or the browser, is closed*/
?>


now, for what you asked, here's the code (add the connect part before)...

<?
$user = $_POST['user']; /*Let's say the user has sent data to connect using a form*/
$pass = $_POST['pass'];

$result = mysql_query("SELECT access FROM table WHERE user='$user' AND pass='$pass'"); /*Check if the user is registred in the database, access being the the access level*/
$nor = @mysql_num_rows($result); /*Check if there is at least one row with the username and the password*/
if ($nor == 0) { /*If there is no 'user AND pass' found, give error*/
echo "Wrong username/password"; /*Put error message here*/
} else { /*Else, if the user is registred and the password is valid*/
$record = $mysql_fetch_row($result); /*Fetch the results so you can use them*/
$_SESSION['access'] = $record[0]; /*Set the access level to the user into the session, so when you want to check again, all you have to check for is if $_SESSION['access'] is high enough (it will be null if the user isn't logged in, check for that too)*/
$_SESSION['user'] = $user; /*Same thing as above, but for the user, so he won't have to re-login everytime*/
if ($access < 2) { /*If the access level is under the level required to view that page... (Change 2 for whatever you want as access level)*/
echo "Access denied"; /*Error message here*/
} else { /*Else, if the access level is high enough to view the page*/
include "includes/page.php"; /*Change that for whatever you want, this is when the access is allowed*/
}
?>

it took me 1h30 to write this 'tutorial' to help you, make good use of it (if you have any error, just tell me, I'll send you fixed code)

any comments or questions? ask them, isn't it the goal of this website?
0
 

Expert Comment

by:EViLWolf
ID: 8085379
**Noticed I was a little bit off topic... I admit I didn't read everything**

for your login script, put a form...
<form method=POST action=yourpage.php?action=login>
<input name=user>
<br><input name=pass type=password>
<br><button type=submit value="Login">
</form>

for signup...
<form method=POST action=yourpage.php?action=signup>
<input name=user>
<br><input name=pass>
<br><input name=retypedpass>
<br><button type=submit value="Signup">
</form>

code... /*No more comments... getting boring!! lol*/
<?
if ($_POST['user'] == '') {
header("Location: errorpage.php");
} else {
$user = $_POST['user'];
}
if ($_POST['pass'] == '') {
header("Location: errorpage.php");
} else {
if ($_POST['pass'] == $_POST['retypedpass']) {
$pass = $_POST['pass'];
} else {
header("Location: errorpage.php");
}
if ($pass = '') { $pass = $_POST['pass']; }
}
/*Done with getting user and pass*/
$action = $_REQUEST['action'];
if ($action == '') { $action = "login"; }

if ($action == 'login') {
/*PUT HERE THE CODE I GAVE YOU LAST POST*/
} else if ($action == 'signup') {
$res = mysql_query("SELECT * FROM table WHERE user='$user'");
$nor = @mysql_num_rows($res);
if ($nor != 0) {
echo "Username already exists";
} else {
mysql_query("INSERT INTO table(user, pass, access) VALUES('$user', '$pass', '0')");
$_SESSION['user'] = $user;
$_SESSION['access'] = 0;
header("Location: page.php");
}
?>

pretty sure there are no mistakes, I'm sorry if there are any... I rarely code for 2 hours in a row without taking a break... that just for you  lol
0
 

Expert Comment

by:EViLWolf
ID: 8085392
where you see things like
if ($var = '') {
the '' isnt a double quote, they are 2 single quotes... '
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8085412
for the past day or so i have been searching to find an easy script for me.  The script is just too complex for a beginner.  i will still give you the points but do you think you could help me with this other script.  if you dont you dont have to.if you do keep reading.

on every one of my pages i have a menu down the left side.  what i want to do is something like what E-E has.  if you are logged in then it will say "Logged in as: Mattjp88"  and then it would have "Logout".  then if you are not logged in i want it to say "Log in".  http://simpleauth.munk.nu/ is the script that i am using.  i tried changing the function checkLoggedIn() in the "functions.php" file.  the function thta i have now is:

function checkLoggedIn($status){
     switch($status){
          // if yes, check user is logged in:
          // ie for actions where, yes, user must be logged in(!)
          case "yes":
              if(!$_SESSION["session"]["loggedIn"]){
               print("login")
               exit;
              }
              break;
             
          // if no, check NOT logged in:
          // ie for actions where user can't already be logged in (ie for joining up or logging in)
          case "no":
               if($_SESSION["session"]["loggedIn"]) {
               print("logout")
               exit;                    
               }
               break;              
     }    
     // if got here, all ok, return true:
     return true;
} // end func checkLoggedIn($status)

-----end-------

i thought if i changed the line that fowarded the person to either "members.php or "login.php" to something that had "login" or "logout" then it would print that on the page.  it doesnt.  i am testing that script here: www.mattjp88.com/login/head/index.php

thank you for all of your help!
Matt :-)
0
 

Expert Comment

by:EViLWolf
ID: 8085472
If you say that what I sent wasn't stuff for a beginner, then you might not be doing what you currently are... oh and I went to your site and it is FOE (full of errors)...
I could help... but I don't think you read what I wrote... sorry
0
 

Expert Comment

by:EViLWolf
ID: 8085488
I'm expert at JavaScript and I can do a program like PHPMyAdmin easily.

Too bad, unsubscribing from this... if you want to contact me, dark_wolf1248@hotmail.com
0
 

Expert Comment

by:EViLWolf
ID: 8085507
And for what you want to do, I have everything you need... just ask and I'll send. I made something like this and it's pretty easy... and you don't need those session.inc.php
0
 
LVL 6

Author Comment

by:mattjp88
ID: 8085545
as it says its "UNDER CONSTRUCTION"
0
 
LVL 15

Expert Comment

by:VGR
ID: 8086765
mattjp88 : not a bad idea. Anyway, my set of scripts (4 files, if I remember correctly) is the one I use and it's not too complicated for a beginner either. It contains a lot of MySql DB access routines/sequences, the ones you requested in your question about "how to use the DB?".
As for setting up the DB, here it is :

I suggest you open up the MySql console (from the command line promt) by typing :
mysql --user=root --password=yourpassword
It should answer with greetings and a prompt
Then type :
CREATE DATABASE yourdatabasename;
(case not important, I just use capitals to emphasize the SQL commands)

USE yourdatabasename;

Now you should think of what you NEED to be in your users table. Fopr example here are mine :
A simple one having no posta address and the strict minimum to online handling :
create table users (id integer unique auto_increment,pseudo char(48),password char(8),admin smallint default 0,email char(40));

a bigger one for a forum I wrote :
create table users (pseudo char(48),password char(8),fond smallint,icone char(24),photo smallint,descriptif text,ipauth char(15),boolSubNet smallint,boolAdmin smallint,refresh smallint default 3600,email char(35),commentaire char(254),etat smallint,CTexte char(6) default 'FFFFFF',CLien1 char(6) default '8080FF',CLienLu char(6) default 'FF0000',CTitre char(6) default 'FFFFFF',CDate char(6) default 'FFFFFF',CAuteur char(6) default 'FFFFFF', CContenu char(6) default 'FFFFFF', CFond char(6) default '000000', clirefresh smallint default 10, msgrefresh smallint default 10, messnb integer default 100,graph smallint default 0,furtif smallint default 0, tempsrep smallint default 0, webcamurl char(254) default '');

an other one for handling postal addresses and some personal information :
create table users (id integer unique auto_increment,pseudo char(48),password char(8),admin smallint default 0,email char(40), dateheure timestamp NOT NULL, adresse1 char(60) default '', adresse2 char(60) default '', codepostal char(8) default '', ville char(20) default '', pays char(20) default '',urlwc char(254) default '',datenaissance date default'', photo1 char(20) default '', photo2 char(20) default '', photo3 char(20) default '',telfixe char(16) default '',telmobile char(16) default '',telbureau char(16) default '',nom char(48) default '',prenom char(48) default '', datefete date default '');

And of course the scripts should reflect the layout of this users table : fields names, number, INSERT INTO commands, SELECT ones, etc. Pretty easy. I recommend you have alook above, choose the fields you would like to have (and that you NEED :D ) to handle your users, then write down on paper the layout , connecting the other tables you plan to use on the users' one. If the check (sufficient data to link efficiently the tables) is OK, then proceed with the CREATE TABLE commands and set up your scripts accordingly.

As for modifying checkLogged() function, you miunderstood it and let me analyse it :

function checkLoggedIn($status){ // why not
    switch($status){ // switch status on 'yes' or 'no' can be transformed in a simple test if ($status), $status being no more 'yes' or 'no' but a Boolean value transmitted as TRUE or FALSE.
         // if yes, check user is logged in:
         // ie for actions where, yes, user must be logged in(!)
         case "yes":
             if(!$_SESSION["session"]["loggedIn"]){ // I find VERY strange this writing. For me AFAIK, it should be $_SESSION["loggedIn"] directly ; By the way, it's EXACTLY the same kind of stuff as in MY script, with session variables $sess_certif, $sess_identif and $sess_pseudo. $sess_pseudo is set to "visitor" whatever the page you try to access (via the include("session.inc.php") being on top of ALL pages...) and if "visitor", some pages (all?) will redirect the unidentified user to the login page
              print("login") // this does ONLY printout "login" in the HTML code... This doesn't provide a LINK to a login function...
              exit;
             }
             break;
             
         // if no, check NOT logged in:
         // ie for actions where user can't already be logged in (ie for joining up or logging in)
         case "no":
              if($_SESSION["session"]["loggedIn"]) {
              print("logout") // the same as above
              exit;                    
              }
              break;              
    }    
    // if got here, all ok, return true:
    return true;
} // end func checkLoggedIn($status)

So : do you want to stick with this partial solution, or do you want me to explain/clear out MY scripts to fit your needs ?
0
 

Expert Comment

by:willhdavison
ID: 8680316
EvilWolf, great script for the login part, its what I needed and is spot on. However I am having an error that I wonder if you can help me with? This is my code for my login screen.

<?php echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">"; ?>
<?php require_once('../Connections/login.php'); ?>
<?
$username = $_POST['user']; /*Let's say the user has sent data to connect using a form*/
$password = $_POST['pass'];

$result = mysql_query("SELECT access FROM test WHERE user='$username' AND pass='$password'"); /*Check if the user is registred in the database, access being the the access level*/
$nor = @mysql_num_rows($result); /*Check if there is at least one row with the username and the password*/
if ($nor == 0) { /*If there is no 'user AND pass' found, give error*/
echo "Wrong username/password"; /*Put error message here*/
} else { /*Else, if the user is registred and the password is valid*/
$record = $mysql_fetch_row($result); /*Fetch the results so you can use them*/
$_SESSION['access'] = $record[0]; /*Set the access level to the user into the session, so when you want to check again, all you have to check for is if $_SESSION['access'] is high enough (it will be null if the user isn't logged in, check for that too)*/
$_SESSION['user'] = $username; /*Same thing as above, but for the user, so he won't have to re-login everytime*/
if ($access < 2) { /*If the access level is under the level required to view that page... (Change 2 for whatever you want as access level)*/
echo "Access denied"; /*Error message here*/
} else { /*Else, if the access level is high enough to view the page*/
include "menu.php"; /*Change that for whatever you want, this is when the access is allowed*/
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body>
 <div align="center">
                    <p><font color="#000000" size="3" face="Arial, Helvetica, sans-serif"><strong>Administration
                      Interface</strong></font><br>
                      <font color="#000000" size="2" face="Verdana, Arial, Helvetica, sans-serif"><br>
                      Enter your User name and Password below to login</font><br>
                      <br>
                      <strong><font color="#CC0000" size="2" face="Verdana, Arial, Helvetica, sans-serif"></font></strong>
                    <form name="form1" method="post" action="">
                      <table width="60%" border="1" cellspacing="0" cellpadding="0">
                        <tr>
                          <td>
<table width="100%" border="0" cellspacing="2" cellpadding="2">
                              <tr>
                                <td width="40%" align="right"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">user
                                  name:</font></td>
                                <td width="60%" align="left"><input name="username" type="text" id="username" maxlength="20"></td>
                              </tr>
                              <tr>
                                <td width="40%" align="right"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">password:</font></td>
                                <td width="60%" align="left"><input name="password" type="password" id="password" maxlength="20"></td>
                              </tr>
                              <tr>
                                <td width="40%" align="right">&nbsp;</td>
                                <td width="60%" align="left"><input type="submit" name="Submit" value="Login"></td>
                              </tr>
                            </table></td>
                        </tr>
                      </table>
                    </form>
</div>
</body>
</html>

---

When I try to run the script I get a parse error saying,

Parse error: parse error, unexpected $ in c:\phpdev5\www\admin\login new.php on line 61.

There obviously isn't any on line 61, I have tried reloading it into another page and retyping the lines but this still doesn't help it. Any ideas, I have ran out of them.

Email me if you want to save running through mattjp88's forum, sorry mate.
Thanks,
John
john@leentech.co.uk
0
 
LVL 15

Expert Comment

by:VGR
ID: 8680712
1) after printing "access denied", you probably want to exit; or redirect to an other page ?!?

2) for the parse error : very easy. See my final comments in the PHP part. I also cleaned up a bit the beginning, and idented+commented the control flow structures :D

<?php
  echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">";
  require_once('../Connections/login.php');

$username = $_POST['user']; /*Let's say the user has sent data to connect using a form*/
$password = $_POST['pass'];

$result = mysql_query("SELECT access FROM test WHERE user='$username' AND pass='$password'"); /*Check if the user is registred in the database, access being the the access level*/
$nor = @mysql_num_rows($result); /*Check if there is at least one row with the username and the password*/
if ($nor == 0) { /*If there is no 'user AND pass' found, give error*/
  echo "Wrong username/password"; /*Put error message here*/
} else { /*Else, if the user is registred and the password is valid*/
  $record = $mysql_fetch_row($result); /*Fetch the results so you can use them*/
  $_SESSION['access'] = $record[0]; /*Set the access level to the user into the session, so when you want to check again, all you have to check for is if $_SESSION['access'] is high enough (it will be null if the user isn't logged in, check for that too)*/
  $_SESSION['user'] = $username; /*Same thing as above, but for the user, so he won't have to re-login everytime*/
  if ($access < 2) { /*If the access level is under the level required to view that page... (Change 2 for whatever you want as access level)*/
    echo "Access denied"; /*Error message here*/
    // here probably exit; or echo "<script>window.url.href=...</script>";
  } else { /*Else, if the access level is high enough to view the page*/
    include "menu.php"; /*Change that for whatever you want, this is when the access is allowed*/
  } // enf if $access<2
} // enf if $nor=0
// you lacked this closing bracket for the IF !!
// IDENT and COMMENT YOUR CODE !!!
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body>
<div align="center">
                    <p><font color="#000000" size="3" face="Arial, Helvetica, sans-serif"><strong>Administration
                      Interface</strong></font><br>
                     <font color="#000000" size="2" face="Verdana, Arial, Helvetica, sans-serif"><br>
                     Enter your User name and Password below to login</font><br>
                     <br>
                     <strong><font color="#CC0000" size="2" face="Verdana, Arial, Helvetica, sans-serif"></font></strong>
                   <form name="form1" method="post" action="">
                     <table width="60%" border="1" cellspacing="0" cellpadding="0">
                       <tr>
                         <td>
<table width="100%" border="0" cellspacing="2" cellpadding="2">
                             <tr>
                                <td width="40%" align="right"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">user
                                  name:</font></td>
                               <td width="60%" align="left"><input name="username" type="text" id="username" maxlength="20"></td>
                             </tr>
                             <tr>
                                <td width="40%" align="right"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">password:</font></td>
                               <td width="60%" align="left"><input name="password" type="password" id="password" maxlength="20"></td>
                             </tr>
                             <tr>
                                <td width="40%" align="right">&nbsp;</td>
                               <td width="60%" align="left"><input type="submit" name="Submit" value="Login"></td>
                             </tr>
                           </table></td>
                       </tr>
                     </table>
                   </form>
</div>
</body>
</html>
0
 

Expert Comment

by:willhdavison
ID: 8681458
Brilliant, thanks, one more thing though (I hope). When the page loads it displays at the top of the screen "Wrong username/password" which I am presuming is the echo for the error above when it can't find the username or password. Does this mean that I need some extra code to stop it executing the script sttraight away? Also what should I put as the action in my form?

Thanks for your help,
John
0
 
LVL 15

Expert Comment

by:VGR
ID: 8681863
yes, of course it should be done differently. I fixed the form of the script, I didn't even realize what it did :D

ok, here it is fixed :

<?php
 require_once('../Connections/login.php');
if (isset($_POST)) { // POSted data received
  if (isset($_POST['submit'])) { // FORM was posted

$username = $_POST['user']; /*Let's say the user has sent data to connect using a form*/
$password = $_POST['pass'];

$result = mysql_query("SELECT access FROM test WHERE user='$username' AND pass='$password'"); /*Check if the user is registred in the database, access being the the access level*/
$nor = @mysql_num_rows($result); /*Check if there is at least one row with the username and the password*/
if ($nor == 0) { /*If there is no 'user AND pass' found, give error*/
 echo "Wrong username/password"; /*Put error message here*/
} else { /*Else, if the user is registred and the password is valid*/
 $record = $mysql_fetch_row($result); /*Fetch the results so you can use them*/
 $_SESSION['access'] = $record[0]; /*Set the access level to the user into the session, so when you want to check again, all you have to check for is if $_SESSION['access'] is high enough (it will be null if the user isn't logged in, check for that too)*/
 $_SESSION['user'] = $username; /*Same thing as above, but for the user, so he won't have to re-login everytime*/
 if ($access >= 2) {/*if the access level is high enough to view the page*/
   include "menu.php"; /*Change that for whatever you want, this is when the access is allowed*/
   exit; // stop rendering here, or else the login FORM will display one more time 8-)
 } else { // else
   echo "Access denied"; /*Error message here*/
   // here probably exit; or echo "<script>window.url.href=...</script>";
  // or leave as is to display the login form again
 } // end if $access<2
} // end if $nor=0
  } // if $submit set
} // if $_POST set
?>
<?xml version="1.0" encoding="iso-8859-1"?".">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body>
<div align="center">
                    <p><font color="#000000" size="3" face="Arial, Helvetica, sans-serif"><strong>Administration
                      Interface</strong></font><br>
                    <font color="#000000" size="2" face="Verdana, Arial, Helvetica, sans-serif"><br>
                    Enter your User name and Password below to login</font><br>
                    <br>
                    <strong><font color="#CC0000" size="2" face="Verdana, Arial, Helvetica, sans-serif"></font></strong>
                  <form name="form1" method="post" action="">
                    <table width="60%" border="1" cellspacing="0" cellpadding="0">
                      <tr>
                        <td>
<table width="100%" border="0" cellspacing="2" cellpadding="2">
                            <tr>
                                <td width="40%" align="right"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">user
                                  name:</font></td>
                              <td width="60%" align="left"><input name="username" type="text" id="username" maxlength="20"></td>
                            </tr>
                            <tr>
                                <td width="40%" align="right"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">password:</font></td>
                              <td width="60%" align="left"><input name="password" type="password" id="password" maxlength="20"></td>
                            </tr>
                            <tr>
                                <td width="40%" align="right">&nbsp;</td>
                              <td width="60%" align="left"><input type="submit" name="Submit" value="Login"></td>
                            </tr>
                          </table></td>
                      </tr>
                    </table>
                  </form>
</div>
</body>
</html>
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question