PHP - Simple Login Script
I've tried Googling this for a long time but I only find complete member systems with ugly code, not something i'm looking for.
What I am looking for is just a simple tutorial or commented code to make a admin login. What it's going to do is just: Loading a MD5 salt hasched password from my MYSQL database. You'll get to fill in one field: Password. If it validates with the MYSQL password it'll show the hidden content; if not it'll just give a "not correct error". That's basicly it. I have only one page of secret admin stuff so yeah.. it would be awesome to have the ability to logout and I of curse want to have everything in sessions! It would be to big help! Similar TutorialsHello, im very green to php and I am having trouble creating a simple log in script. Not sure why this is not working, maybe a mysql_query mistake? I am not receiving any errors but nothing gets updated in the members table and my error message to the user displays. any help is appreciated! here is my php: <?php session_start(); $errorMsg = ''; $email = ''; $pass = ''; if (isset($_POST['email'])) { $email = ($_POST['email']); $pass = ($_POST['password']); $email = stripslashes($email); $pass = stripslashes($pass); $email = strip_tags($email); $pass = strip_tags($pass); if ((!$email) || (!$pass)) { $errorMsg = '<font color="#FF0000">Please fill in both fields</font>'; }else { include 'scripts/connect_db.php'; $email = mysql_real_escape_string ($email); $pass = md5($pass); $sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$pass'"); $log_check = mysql_num_rows($sql); if ($log_check > 0) { while($row = mysql_fetch_array($sql)) { $id = $row["id"]; $_SESSION['id']; $email = $row["email"]; $_SESSION['email']; $username = $row["username"]; $_session['username']; mysql_query("UPDATE members SET last_logged=now() WHERE id='$id' LIMIT 1"); }//Close while loop echo "You are logged in"; exit(); } else { $errorMsg = '<font color="#FF0000">Incorrect login data, please try again</font>'; } } } ?> and the form: <?php echo $errorMsg; ?> <form action="log_in.php" method="post"> Email:<br /> <input name="email" type="text" /><br /><br /> Password:<br /> <input name="password" type="password" /><br /><br /> <input name="myBtn" type="submit" value="Log In" /> </form> I'm very new to PhP and one of my asignments in class is to create a simple login using php and mysql. I made a simple page using html, php, and mysql and i keep getting errors. Here is my code so far: This is my index.php page: <html> <form action = 'login.php' method='POST'> Username: <input type='text' name='username'><br> Password: <input type='password' name='password'><br> <input type='submit' value='Log in'> </form> </html> This is my login.php page: <?php $username = $_POST['username']; $password = $_POST['password']; if ($username&&$password) { &connect = mysql_connect("localhost", "root", " ") or die ("Couldnt connect"); mysql_selct_db("phplogin") or die("Couldn't find db"); } else die ("Please enter a username and password"); ?> mySql file is very basic: 3 columns, id, username, password I dont think my problem is with the mySQL page that was the easiest to make but everytime I hit login in the index.php, the entire script for login.php gets outputted on screen. I would appreciate all the help. I have a form on my website which actions login.php. The login.php code is below: <?php include('includes/classes.php.inc'); session_start(); $link = new BaseClass(); $data = $link->query("SELECT * FROM logins"); $pass_accepted = false; if($_REQUEST['username'] && $_REQUEST['password']){ $username = $_REQUEST['username']; $password = $_REQUEST['password']; while($row = mysql_fetch_array($data)){ if(($row['username']==$useranme)&&($row['password']==$password){ echo 'Password correct!'; $_SESSION['loggedin']=true; $pass_accepted = true; } } } else { echo 'You did not enter a username or password!'; } if(!$pass_accepted){ echo 'Your password is incorrect'; } echo '<br>Please <a href="index.php">click here</a> to return to page'; ?> I have checked that my references are all correct however even when I enter the correct password it returns saying the password is incorrect. Any idea on why this could be? I am happy to answer any follow up questions. Regards Hi Everyone, Just wondered if someone could quickly help me out, im building a simple login system for my website but having a little bit of trouble, the error i keep getting is: Quote Cannot modify header information - headers already sent by (output started at /home/sites/cuju8.com/public_html/include.php:18) in /home/sites/cuju8.com/public_html/login.php on line 12 I have done some research but cant find the answer to this, my login script is as follows: Code: [Select] <?php require_once('include.php'); $error = ''; $form = $_POST['submit']; $email = $_POST['email']; $password = $_POST['password']; if( isset($form) ) { if( isset($email) && isset($password) && $email !== '' && $password !== '' ) { $sql = mysql_query("SELECT * FROM `usersystem` WHERE email='$email' and password='$password';"); if( mysql_num_rows($sql) != 0 ) { //success $_SESSION['logged-in'] = true; [b]header('Location: members.php');[/b] exit; } else { $error = "Incorrect login info"; } } else { $error = 'All information is not filled out correctly';} } ?> I think its the header location code thats causing the problem but im not sure where to move it too. If anyone could help i would really appreciate it. Cheers Hi there, I have a simple login script written but I get an error with it. It does work but shows an error on some pages. Let me explain. Three Files: Admin.php Login.html checklogin.php When the user has logged in they go to checklogin.php. If the username and password match 1 row in the database then it forwards the user to admin.php fine. Except I keep getting mysql warning messages: Warning: Cannot modify header information - headers already sent by (output started at /home/wormste1/public_html/tilburywebdesign/shop/templates/template1/admin/updatescompanyinformation.php:3) in /home/wormste1/public_html/tilburywebdesign/shop/templates/template1/admin/companyinfoupdated.php on line 3 At the start of each page I want password protected I put the following code: <? session_start(); if(!session_is_registered(myusername)){ header("location:login.html"); } ?> I can't work out why I am getting this error. Many Thanks, Ian Hey I would just like to release a simple login/register script that will work just fine and has some nice systems in it. The Login. (I will post the code then below tell you what you need to do to get it to work with MYSQL DATABASE) Create a file and call it login with the suffix .php so if you have file extensions showing on your computer it will look like "login.php" then put this code inside of it. Code: [Select] <?php session_start(); ?> <?php function mysql_prep($value) { $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysql_real_escape_string"); // i.e PHP >= v4.3.0 if($new_enough_php){ // PHP v4.3.0 or higher if ($magic_quotes_active){ $value = stripslashes($value); } $value = mysql_real_escape_string($value); }else{ //Before PHP v4.3.0 //if magic quotes aren't already on then add slahes manually if(!$magic_quotes_active){ $value = addslashes($value); } // if magic quotes are active then the slashes already exist } return $value; } function redirect_to($location = NULL){ if($location != NULL){ header("Location: {$location}"); exit; } } define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS","yourpassword"); define("DB_NAME","yourdatabasename"); $connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS); if(!$connection){ die("Database Connection Failed: " . mysql_error()); } $db_select = mysql_select_db("bcooperz", $connection); if(!$db_select){ die("Connection to database failed: " . mysql_error()); } ?> <?php if(isset($_SESSION['user_id'])){ redirect_to("staff.php"); } ?> <?php if (isset($_POST['submit'])){ $errors = array(); // Perform validations on the form $required_fields = array('username', 'password'); foreach($required_fields as $fieldname){ if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])){ $errors[] = $fieldname; } } $field_with_lengths = array('username' => 30, 'password' => 30); foreach($field_with_lengths as $fieldname => $maxlength) { if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; } } $username = trim(mysql_prep($_POST['username'])); $password = trim(mysql_prep($_POST['password'])); $hashed_password = sha1($password); if (empty($errors)){ // Checks database to see if username and password exist their $query = "SELECT id, username FROM users WHERE username='$username' AND hashed_password='$hashed_password' LIMIT 1"; $result_set = mysql_query($query, $connection); if(!$result_set){ die("Database Query Failed: " . mysql_error()); } if (mysql_num_rows($result_set) == 1) { // The Username and Password have been found in the database and the user is verified // Only 1 Match $found_user = mysql_fetch_array($result_set); $_SESSION['user_id'] = $found_user['id']; $_SESSION['username'] = $found_user['username']; redirect_to("staff.php"); }else{ // Username and Password was not found in the database. $message = "Username/Password Combination Incorrect.<br/>Please make sure your caps lock key is off and try again."; echo $message; } }else{ $count = count($errors); if($count == 1){ echo "Their Was {$count} Error In The Form" . "<br />"; print_r(implode(", ", $errors)); }else{ echo "Their Was {$count} Error's In The Form" . "<br />"; echo "<b>"; print_r(implode(", ", $errors)); echo "</b>"; } } }else{ // The Form Has Not Been Submitted if(isset($_GET['logout']) && $_GET['logout'] == 1){ echo "You Are Now Logged Out"; } if(isset($_GET['nowlogged']) && $_GET['nowlogged'] == 1){ echo "You Need to Login to reach this page."; } $username = ""; $password = ""; } ?> <html> <head> <title>Register</title> </head> <body> <form action="login.php" method="post"> Username : <input type="text" name="username" maxlength="30" value="<?php echo htmlentities($username); ?>" /><br /> Password : <input type="password" name="password" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br /><br /> <input type="submit" name="submit" value="Login" /><br /> </form> <p>Haven't got an account? register <a href="register.php">here!</a></p> </body> </html> Now once you have a file called "login.php" with the above code inside of it you will need to goto your mysql database and create a database with a table that has 3 fields in the following format. - id - int(11) - Auto increment - username - varchar(50) - hashed_password - varchar(40) Now search for this in the login.php code Code: [Select] define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS","yourpassword"); define("DB_NAME","yourdatabasename"); And This: Code: [Select] $db_select = mysql_select_db("bcooperz", $connection); And change these to your settings. Once you have done all this create a new file called register with the suffix .php as well so if you have file extensions turned on it will look like "register.php" And add this code inside it: Code: [Select] <?php function mysql_prep($value) { $magic_quotes_active = get_magic_quotes_gpc(); $new_enough_php = function_exists("mysql_real_escape_string"); // i.e PHP >= v4.3.0 if($new_enough_php){ // PHP v4.3.0 or higher if ($magic_quotes_active){ $value = stripslashes($value); } $value = mysql_real_escape_string($value); }else{ //Before PHP v4.3.0 //if magic quotes aren't already on then add slahes manually if(!$magic_quotes_active){ $value = addslashes($value); } // if magic quotes are active then the slashes already exist } return $value; } function redirect_to($location = NULL){ if($location != NULL){ header("Location: {$location}"); exit; } } ?> <?php define("DB_SERVER","localhost"); define("DB_USER","root"); define("DB_PASS","maxcooper"); define("DB_NAME","bcooperz"); $connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS); if(!$connection){ die("Database Connection Failed: " . mysql_error()); } $db_select = mysql_select_db("bcooperz", $connection); if(!$db_select){ die("Connection to database failed: " . mysql_error()); } ?> <?php if(isset($_POST['submit'])){ $username = trim(mysql_prep($_POST['username'])); $password = trim(mysql_prep($_POST['password'])); $hashed_password = sha1($password); $confirmpass=$_POST['confirmpass']; $query2 = "SELECT * FROM users WHERE username='$username'"; $result2 = mysql_query($query2); $counted=mysql_num_rows($result2); $errors = array(); // Perform validations on the form $required_fields = array('username', 'password', 'confirmpass'); foreach($required_fields as $fieldname){ if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])){ $errors[] = $fieldname; } } if($confirmpass!=$_POST['password']){ $errors[] = "passdifference"; } if($counted > 0){ $errors[] = "User Already Created"; } $field_with_lengths = array('username' => 30, 'password' => 30); foreach($field_with_lengths as $fieldname => $maxlength) { if (strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength) { $errors[] = $fieldname; } } /* The Form Has Been Submitted */ if (empty($errors)){ $query = "INSERT INTO users (username,hashed_password) VALUES ('{$username}', '{$hashed_password}')"; $result = mysql_query($query, $connection); if($result){ echo "User Successfully Created"; }else{ echo "The User Could Not Be Created" . "<br />"; echo mysql_error(); } }else{ $count = count($errors); if($count == 1){ echo "Their Was {$count} Error In The Form" . "<br />"; print_r(implode(", ", $errors)); }else{ echo "Their Was {$count} Error's In The Form" . "<br />"; echo "<b>"; print_r(implode(", ", $errors)); echo "</b>"; } } }else{ /* The Form Has Not Yet Been Submitted */ $username = ""; $password = ""; } ?> <html> <head> <title>Register</title> </head> <body> <form action="register.php" method="post"> Username : <input type="text" name="username" maxlength="30" value="<?php echo htmlentities($username); ?>" /><br /> Password : <input type="password" name="password" maxlength="30" value="<?php echo htmlentities($password); ?>" /><br /> Confirm Password: <input type="password" name="confirmpass" maxlength="30" value="" /><br /><br /> <input type="submit" name="submit" value="Register" /><br /> </form> <p>Already have a account? login here <a href="login.php">here!</a></p> </body> </html> Once you have done that and you have a file called "register.php" you will need to perform the final step which will be changing the database details once again on the second file ("register.php"). Thanks, Bcooperz. Please tell me if this works ok..ive done this a million times..i have a working example here and i copied it and amended it for this new project but for some reason i cant get a form to post data to another page. this is the error message i get Notice: Undefined index: username in C:\wamp\www\uni\fyp\site\mobile\login.php on line 16 Notice: Undefined index: password in C:\wamp\www\uni\fyp\site\mobile\login.php on line 17 here is my form code: <form method="post" action="login.php"> <table align="center" cellpadding="0" cellspacing="0"> <tr> <td style="vertical-align:top;">Username: </td><td><input type="text" name="username" value="" /></td> </tr> <tr> <td style="vertical-align:top;">Password: </td><td><input type="password" name="password" value="" /><br /><input type="submit" id="submit" value="Login" /></td> </tr> </table> </form> and here is the code within the login.php where the form should post to $username = $_POST['username']; $password = $_POST['password']; // Help protect against MySQL injection $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); // Selecting data from database where correct username and password are found $sql="SELECT * FROM customer WHERE username='$username' and password='$password'"; $result=mysql_query($sql) or die(mysql_error()); i cant see anything wrong..been looking for hours...please please help me Hello guys, Is there on web any updated tutorial on how can I add Facebook login on my simple php login script? Dear PHPFreaks, I am new to PHP. Currently I'm trying to get a PHP login to write to file and use that file to register member and then allow users to login by reading through the file. Here is the code so far. Any help would be grateful. <body> <form action="register.php" method="post"> <h2>Register:</h2> <p> <label for="runame">Username:</label> <input name="runame" id="runame" value="" type="text" /> </p> <p> <label for="rpword">Password:</label> <input name="rpword" id="rpword" type="password" /> </p> <p> <input name="register" value="Register here" type="submit" /> </p> </form> </body> register.php <?php if (isset($_POST['submit'])) { $runame = $_POST['uname']; $rpword = $_POST['pword']; $category = "user"; } $fh = fopen("password.txt","a+"); $data = $runame . ":" . $rpword . ":" . $category . "\n"; fwrite($fh, $data); fclose($fh); ?> Hello, I created a simple login script, taht has a hard coded user/pass. Yet for some reason it will not work, keeps redirecting to the main login page Here is the code Login Page Code: [Select] <table width='400' border='0' align='center' cellpadding='0' cellspacing='0'> <tr> <td>UserName:</td> <td><form action="loginscript.php" method="post"> <input name="username" type="text" size="10"></td> </tr> <tr> <td>Password:</td> <td><input name="password" type="password" size="10"></td> </tr> <tr> <td colspan='2' align='center'><input name="Submit" type="submit" value="Submit"></form></td> </tr> </table> Login Script Code: [Select] <?php session_start(); $pass = strtolower($_POST['password']); $name = strtolower($_POST['username']); if($name == "test" && $pass == "test"){ header ("location: select.php"); } else{ // invalid login, so go back ... header ("location: index.php"); } ?> Select.php Code: [Select] <?php session_start(); if(isset($_SESSION['myuser'])){ } else{ header ("location: index.php"); } ?> ANy ideas why it is not working. It doesnt seem like it is going through the login on the loginscript as all it does is redirect back to index page over and over again I am trying to learn php and I cannot figure out how to get a simple login form going. I am getting this error.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
I have no clue what I am doing wrong. I am following the "HowTo".
Here is my code
Index.php ( Login Form )
<form name="form1" method="post" action="checklogin.php"> <div id="wrappermiddle"> <h2>Login</h2> <div id="username_input"> <div id="username_inputleft"></div> <div id="username_inputmiddle"> <input name="myusername" type="text" id="myusername" value="Email Address"> <img id="url_user" src="./images/mailicon.png" alt=""> </div> <div id="username_inputright"></div> </div> <div id="password_input"> <div id="password_inputleft"></div> <div id="password_inputmiddle"> <input name="mypassword" type="text" id="mypassword" value="Password"> <img id="url_password" src="./images/passicon.png" alt=""> </div> <div id="password_inputright"></div> </div> <div id="submit"> <input type="image" src="./images/submit.png" name="Submit" value="Login"> </form> </div>checklogin.php <?php $host="localhost"; // Host name $username="MY DB USER"; // Mysql username $password="Password"; // Mysql password $db_name="MY DB Name"; // Database name $tbl_name="admin"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?>Any help would be greatly appreciated. Edited by Oblivion13, 07 October 2014 - 05:25 PM. I have a Login page which i want to check if the user details (username, password and activation) are valid then redirect user dependent on his/her "accessLevel" (admin, member and none)
Admin will be directed to "index.php"
Member will be directed to "tasks.php"
and none will be redirected to "notActive.php"
here is my current code which half works;
<?php include ('connect.php'); if(isset($_POST['submit'])) { // Initialize a session: session_start(); // Define $username and $password $username=$_POST['username']; $password=$_POST['password']; // To protect MySQL injection $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM ecmt_members WHERE username='$username' and password='$password' AND Activation IS NULL"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $username and $password, table row must be 1 row if($count==1){ // Register $username, $password and redirect to file "index.php" $role = mysql_fetch_array($result); $_SESSION['username']= $username; $_SESSION['password']= $password; //$_SESSION['role']= $role['accessLevel']; if($role['accessLevel'] == "admin"){ $_SESSION['adminuser']=$role['accessLevel']; header("location:index.php"); exit(); } elseif($role['accessLevel'] == "member"){ $_SESSION['user']=$role['accessLevel']; header("location:tasks.php"); exit(); } else { echo "Error: Username, Password or Access Level incorrect! Go Home, you're Drunk!!!"; } } } // End of the main Submit conditional. ?><!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>Login Form</title> <!-- jQUERY --> <script src="//code.jquery.com/jquery-latest.js"></script> <!-- Add Main CSS --> <link rel="stylesheet" type="text/css" href="../tool/css/main.css"> <!-- Font-Awesome --> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <style> body { background: url(../tool/images/bg1.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .exactCenter { width:auto; height:auto; position: fixed; top: 50%; left: 50%; margin-top: -200px; ; } </style> </head> <body> <div class="exactCenter"> <div id="login-container"> <img src="../tool/images/bigLogo.png" /><br /> <form action="login.php" method="post" class="form"> <fieldset class="group"> <input class="input" type="text" id="username" name="username" size="25" placeholder="username"/> <img src="../tool/images/spacer.png" width="5" height="5" /> <input class="input" type="password" id="password" name="password" size="25" placeholder="password"/> <img src="../tool/images/spacer.png" width="5" height="5" /> </fieldset> <input type="hidden" name="formsubmitted" value="TRUE" /> <button type="submit" name="submit" class="btn btn-blue" ><i class="fa fa-unlock-alt"></i> Login</button> <img src="../tool/images/spacer.png" width="5" height="5" /> <a href="Register.php"><button type="button" class="btn btn-green" ><i class="fa fa-hand-o-up"></i> Register</button></a> </form> </div></div> </body> </html>When i test it with admin login credentials i get the page refresh again without error, when i login with member credentials it shows tasks.php and when i try to log in with unactivated account "acivation column is not NULL" i get a page refresh also with no error. Can someone help me make it work for each role and perhaps have some sort of error reporting depending on error. im pulling my hair out here and this is the first time i have worked with login conditions, and im VERY confused. Edited by jacko_162, 28 October 2014 - 05:12 PM. Hi can someone pls help, im tryin a tutorial but keep getting errors, this is the first one i get after registering. You Are Registered And Can Now Login Warning: Cannot modify header information - headers already sent by (output started at /home/aretheyh/public_html/nealeweb.com/regcheck.php:43) in /home/aretheyh/public_html/nealeweb.com/regcheck.php on line 46 Hello everyone: I wanted to see how I can make a simple login page (user name and password) that redirects to a page(s) if the login is correct. Also, I wanted to put protection on the page(s) that will send the user back to the login page if the credentials are nor correct. I would imagine the username/password would be stored in a database table (Admins), and the correct login info would be stored in a session ..? I am use to doing this with ASP, but never PHP. I want to make sure I understand how to do this properly and securely so I can use this as a model for other systems. In ASP I would do a protected page like this: a_login_check.asp Code: [Select] <% if session("admin_user_name") = "" then session.abandon response.redirect "login.asp" end if %> Protected-Page.asp Code: [Select] <!-- #include file="include/a_check_login.asp" --> <html> ... CONTENT ... </html> And of course there is the login page itself ... (I thought it would be nice to add a "Forgot Password" link on the login page, but if that is too complicated I can do that later .. or is it easy ??) Anyway, can someone point-out to me how to do this. I would appreciate it! Hey so this is my login script but when i enter something into the username and password box and submit it, the page just refreshes.
<?php echo " <h1>LOGIN</h1> <form action='' method='POST'> <table> <tr> <td> <b>Username:</b> </td> <td> <input type='text' name='username' placeholder='Enter your username'> </td> </tr> <tr> <td> <b>Password:</b> </td> <td> <input type='password' name='password' placeholder='Enter your password'> </td> <td> <input type='submit' value='login' name='submit'> </td> </tr> </form> "; $host = "localhost"; $username = "root"; $password = ""; $db_name = "website"; mysql_connect("$host", "$username", "$password") or die("Could not connect"); mysql_select_db("$db_name") or die("Could not find database"); if(isset($_POST['submit'])) { if(!empty($_POST['username'])) { $sql = "SELECT * FROM members WHERE username='$username' AND password='$password'"; $result = mysql_query($sql); $count = mysql_num_rows($result); if($count==1) { $row = mysql_fetch_array($sql); $bancheck = mysql_query($row); if($row['active']==0 && count==0) { include 'userban.html'; } else if($count==1 && $bancheck==1) { $_SESSION['username'] = "$username"; include '/home/user/index.php'; } else { echo "You entered invalid information"; } } } } ?> Hi! I need help with the login script i wrote. Please help me get it working. The section related to guest works fine however it always gives me error message when i get to the queryA and queryB stages. Thanks! I've already got the database running, using MySQL. Name of database - connectiontracker; tables- user_admin, user_user Here's the script: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/xhtml1-loose.dtd"> <?php session_start(); $userType = $_POST["userType"]; $userName = $_POST["username"]; $passWord = $_POST["password"]; $link = mysqli_connect("localhost", "ct1", "ctcfgb") Or die('Could not connect '. mysqli_error()); switch ($userType) { case "admin": if (isset($userName) && isset($passWord)) { $dbTableA = "user_admin"; mysqli_select_db($link, "connectiontracker") Or die ("Database unavailable"); $queryA = "SELECT * FROM $dbTableA WHERE username='$userName' AND password='$passWord'"; $resultA = mysqli_query($queryA) or die("Verification Error A"); if(mysqli_num_rows($resultA) == 1) { $_SESSION = true; header ('Location: welcomeadmin.php'); } else echo "Incorrect administrator username and/or password"; } break; case "user": if (isset($userName) && isset($passWord)) { $dbTableB = "user_user"; mysqli_select_db($link, "connectiontracker") Or die ("Database unavailable"); $queryB = "SELECT * FROM $dbTableB WHERE username='$userName' AND password='$passWord'"; $resultB = mysqli_query($queryB) or die("Verification Error B"); if(mysqli_num_rows($resultB) == 1) { $_SESSION = true; header ('Location: welcomeuser.php'); } else echo "Incorrect Organization/Individual username and/or password"; } break; case "guest": header ('Location: welcomeguest.php'); break; } if (!isset($_POST['Enter'])) { ?> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Login to Connection Tracker</title> <!-- <link rel="stylesheet" href="ct_style1.css" type="text/css"> --> </head> <body> Please select from the following: <br /> <form action="<?php echo $PHP_SELF;?>" method="post"> <select name="userType"> <option value="admin">Administrator</option> <option value="user" selected>Organization</option> <option value="guest">Guest</option> </select> <br /> Please leave the following fields blank if entering the system as Guest <br /> Username: <input type="text" name="username"> <br /> Password: <input type="text" name="password"> <input type="submit" name="Enter"/> <br /> </form> </body> </html> <?php } mysqli_close($link); ?> Hello everyone, I have just finished coding a logion/register/logout script. I am quite new to PHP (this was my first task to begin the learning process!). The scripts now work fine and gets the job done. It incorporates a database and has a number of checks in place. I know that the code is probably pretty ugly however and not as efficient as it could be. Could anyone suggest places where I could improve it or security issues with it? I have tried to secure it against sql injection; it also ensures that no fields are blank and that the two passwords in registration are the same and I have also made username a unique field in database. Thanks in advance for any help or guidance. Here are the scripts: index.html, checklogin.php, register.php, menu.php, and logout.php <html> <body> <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="input" action="checklogin.php" method="post"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3"><strong>Member Login </strong></td> </tr> <tr> <td width="78">Username</td> <td width="6">:</td> <td width="294"><input name="username" type="text" id="username"></td> </tr> <tr> <td>Password</td> <td>:</td> <td><input name="password" type="password" id="mypassword"></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="login" value="Login"></td> </tr> </table> </td> </form> </tr> </table> <center>Not a member? <a href="./register.php">Register!</a></center> </body> </html> <?php $host="localhost"; $usr="root"; $pwd="******"; $db="*****"; $tbl_name="members"; mysql_connect($host, $usr, $pwd) or die(mysql_error()); mysql_select_db($db) or die(mysql_error()); $initialusr = $_POST['username']; $initialpwd = $_POST['password']; $secondusr = stripslashes($initialusr); $secondpwd = stripslashes($initialpwd); $pswd = mysql_real_escape_string($secondpwd); $myusr = mysql_real_escape_string($secondusr); $mypswd= md5($pswd); $sql="SELECT *FROM $tbl_name WHERE username='$myusr' and password='$mypswd'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if ($count==1) { session_start(); $_SESSION['username'] = $myusr; header("location:menu.php"); } else { echo "Incorrect Username or Password"; } ?> <?php $host="localhost"; $usr="root"; $pwd="*****"; $db="***********"; $tbl_name="members"; mysql_connect($host, $usr, $pwd) or die(mysql_error()); mysql_select_db($db) or die(mysql_error()); if (isset($_POST['register']) && $_POST['username'] && $_POST['password'] && $_POST['confirm'] && $_POST['email'] && $_POST['password'] == $_POST['confirm']) { $pwd = mysql_real_escape_string("$_POST[password]"); $md5pwd = md5("$pwd"); $usr = mysql_real_escape_string("$_POST[username]"); $email = mysql_real_escape_string("$_POST[email]"); $query = "INSERT INTO members (username, password, email) VALUES('$usr', '$md5pwd', '$email')"; mysql_query($query) or die(mysql_error()); mysql_close(); echo "You have successfully registered!"; } else{ ?> <html> <body> <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="input" action="register.php" method="post"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3"><strong>Register</strong></td> </tr> <tr> <td width="78">Username</td> <td width="6">:</td> <td width="294"><input name="username" type="text" id="username"></td> </tr> <tr> <td>Password</td> <td>:</td> <td><input name="password" type="password" id="password"></td> </tr> <tr> <td>Confirm Password</td> <td>:</td> <td><input name="confirm" type="password" id="confirm"></td> </tr> <tr> <td>Email</td> <td>:</td> <td><input name="email" type="text" id="email"></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="register" value="Register"></td> </tr> </table> </td> </form> </tr> </table> </body> </html> <?php } ?> <?php session_start(); if (!isset($_SESSION['username'])){ header("location:index.html"); } else { ?> <html> <body> <?php $username = $_SESSION['username']; echo "Welcome " . $username . " !"; ?> <br /> <a href = logout.php>Log out</a> </body> </html> <?php } ?> <?php session_start(); session_destroy(); header("location:index.html") ?> Hi all again, This script was working perfectly but I have not got a clue what changed in it or how and can not seem to find the problem. The connection works, email and password variables match the mysql databases so must be my Syntax. appreciate if you can help. <?php include("../cxn.php"); $sql = "SELECT password FROM Members WHERE email='$_POST[email]'"; $result = mysqli_query($cxn,$sql) or die ("Couldn't execute query1"); $num = mysqli_num_rows($result); if ($num >0) // Login Name found { $sql = "SELECT * FROM Members WHERE email='$_POST[email]' AND password=md5('$_POST[password]')"; $result2 = mysqli_query($cxn,$sql) or die ("Couldn't execute query2"); $num2 = mysqli_num_rows($result2); if ($num2 > 0) // password correct { session_start(); $_SESSION['auth']="yes"; $_SESSION['logname'] = $_POST['email']; $logname = $_SESSION['logname']; $today = date("Y-m-d h:i:s"); $sql = "INSERT INTO Login (email,loginTime) VALUES ('$logname', '$today')"; $result = mysqli_query($cxn,$sql) or die ("Can't execute insert query"); echo "you have logged in!"; header("Location: ../$_POST[page]"); } else { $message = "The email address, '$_POST[email]' is registered, but you have not entered the correct password! Please try again.<br>"; include("../login.html"); } } ?> Hey everyone. I currently have a login script that uses cookies to check if the user is logged in. But I have been told that even if I have used md5() then the the password is still at risk, so I was wondering if using sessions would be better, or if there was some way to make the passwords in the cookies more secure? Here is the code I currently have to secure passwords in the cookie: Code: [Select] $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } |