PHP - Encrypted Password Not Recognized By Database During Registered Member Login
Hello Everyone,
I recent made a simple membership website. Every page I created works exactly how I envisioned it... All members data from my registration form goes into my database along with their md5 Encrypted passwords with a time-stamp. Subsequent pages have a start_session included. I am very please with it except ONE THING. Logging in is now a problem... username is recognized but NOT the password. Now the strange thing is that when I go into the database and copy the encrypted password and paste it into the password field in my login page, I miraculously get into my website with NO problem. " How do I get the registered members Encrypted Passwords to be recognized by the database when the registered members decide to logging in with the password that they create? " Is there a easy fix for this? I appreciate ALL your help... thanks mrjap1 Similar Tutorialsless than 6 characters. I think it's the way my code is ordered. I've tried switching the commands around, no luck. Help please. Code: [Select] <?php //begin register script $submit = $_POST['submit']; //form data $username= strip_tags ($_POST['username']); $email= strip_tags($_POST['email']); $pwd= strip_tags($_POST['pwd']); $confirmpwd= strip_tags($_POST['confirmpwd']); $date = date("Y-m-d"); if ($submit) { //check for required form data if($username&&$pwd&&$confirmpwd&&$email) { //check length of username if (strlen($username)>25||strlen($username)<6) { echo "<p class='warning'>username must be bewteen 6 and 25 characters</p>"; } else { //check password length if (strlen($pwd)>25||strlen($pwd)<6) { echo "<p class='warning'>password must be between 6 and 25 characters</p>"; } else { //register the user echo "<p class='success'>Thanks for signing up!</p>"; } } //check if passwords match if ($pwd==$confirmpwd) { } else { echo "<p class='warning'>your passwords do not match</p>"; } //encrypt password $pwd = md5($pwd); $confirmpwd = md5($confirmpwd); //open database $connect = mysql_connect("xxxxxxxx", "xxxxxxxx", "xxxxxxxx"); mysql_select_db("digital"); //select database //register the user $queryreg = mysql_query(" INSERT INTO users VALUES ('','$username', '$email', '$pwd') "); die("<p class='success'>Thank you for signing up you have been registered"); } else { echo "<p class='warning'>please fill in all fields</p>"; } } ?> <?php
require_once('upper.php'); require_once('database.php'); echo $error_msg=''; if(isset($_POST['submit'])) { $LoginId=mysqli_real_escape_string($dbc,trim($_POST['LoginId'])); $Password1=mysqli_real_escape_string($dbc,trim($_POST['Password1'])); $Password2=mysqli_real_escape_string($dbc,trim($_POST['Password2'])); $Name=mysqli_real_escape_string($dbc,trim($_POST['Name'])); $Age=mysqli_real_escape_string($dbc,trim($_POST['Age'])); $BloodGroup=mysqli_real_escape_string($dbc,trim($_POST['BloodGroup'])); if(!isset($_POST['Sex'])) { echo 'Please enter Sex<br>'; } else{ $Sex= mysqli_real_escape_string($dbc,trim($_POST['Sex'])); } $Qualification=mysqli_real_escape_string($dbc,trim($_POST['Qualification'])); $ContactNumber=mysqli_real_escape_string($dbc,trim($_POST['ContactNumber'])); $Email=mysqli_real_escape_string($dbc,trim($_POST['Email'])); $Address=mysqli_real_escape_string($dbc,trim($_POST['Address'])); $AboutYourself=mysqli_real_escape_string($dbc,trim($_POST['AboutYourself'])); //$countCheck=count($_POST['checkbox']); //echo $countCheck; //$checkbox=$_POST['checkbox']; //$countCheck=count($checkbox); if(empty($LoginId)){echo 'Please enter Login Id';} elseif(empty($Password1)){echo 'Please enter Password';} elseif(empty($Password2)){echo 'Please confirm Password';} elseif($Password1!==$Password2){echo 'Password didn\'t match';} elseif(empty($Name)){echo 'Please enter Name';} elseif(empty($Age)){echo 'Please enter Age';} elseif(!isset($_POST['Sex'])){} elseif(empty($Qualification)){echo 'Please enter Qualification';} elseif(empty($ContactNumber)){echo 'Please enter Contact Number';} elseif(empty($Email)){echo 'Please enter Email';} elseif(empty($Address)){echo 'Please enter Address';} elseif(empty($AboutYourself)){echo 'Please enter About Yourself';} elseif(!isset($_POST['checkbox'])){ echo 'You have to register at least one activity.';} elseif(!isset($_POST['TermsAndConditions'])){ echo 'You have to agree all Terms and Conditions of Elite Brigade.';} else { require_once('database.php'); $query="select * from registration where LoginId='$LoginId'"; $result=mysqli_query($dbc,$query); if(mysqli_num_rows($result)==0) { $checkbox=$_POST['checkbox']; $countCheck=count($_POST['checkbox']); $reg_id=' '; for($i=0;$i<$countCheck;$i++) { $reg_id=$reg_id.$checkbox[$i].','; $query="insert into activity_participation (LoginId,Title,Date) values ('$LoginId','$checkbox[$i]',CURDATE())"; $result=mysqli_query($dbc,$query) or die("Not Connected"); } $query="insert into registration (LoginId,Password,Name,Age,BloodGroup,Sex,Qualification,ContactNumber,Email,Address,AboutYourself,Activity)values ('$LoginId'[B],SHA('$Password1'),[/B]'$Name','$Age','$BloodGroup','$Sex','$Qualification','$ContactNumber','$Email','$Address','$AboutYourself',',$reg_id')"; $result=mysqli_query($dbc,$query) or die("Not Connect"); echo ' Dear '.$Name.'.<br>Your request has been mailed to admin.<br>Your account is waiting for approval<br>'; $from= 'Elite Brigade'; $to='ankitp@rsquareonline.com'; $subject='New User Registration'; $message="Dear admin,\n\nA new user request for registration. Please check it out.\n\nRegards\nMicro"; mail($to,$subject,$message,'From:'.$from); //header('Location: index.php'); // header('Location: Registration.php'); } else { echo 'Dear '.$Name. ', <br> An account already exist with login-id<b> '.$LoginId.'</b> <br>Please try another login-id'; }} } ?> <html> <head> <script src="jquery-latest.js"></script> <script type="text/javascript" src="jquery-validate.js"></script> <style type="text/css"> * { font-family: Verdana; } label.error { color: white; padding-left: .5em; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> <script> $(document).ready(function(){ $("#commentForm").validate(); }); </script> </head> <body> <?php echo $error_msg; ?> <form action='<?php echo $_SERVER['PHP_SELF'];?>' id="commentForm" method='post'> <div class="registration_and_activity"> <table border="0" width="380"> <tr><td colspan="2"> <h3>New User?</h3></td></tr> <tr><td width="120"> <em>*</em>Enter Login id</td><td width="150"><input type='text' name='LoginId' minlength="4" value='<?php if(!empty($LoginId))echo $LoginId;?>' /></td></tr> <tr><td> <em>*</em>Enter Password</td> <td><head> <div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> <SCRIPT language=Javascript> function capLock(e){ kc = e.keyCode?e.keyCode:e.which; sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false); if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)) document.getElementById('divMayus').style.visibility = 'visible'; else document.getElementById('divMayus').style.visibility = 'hidden'; } </SCRIPT> </HEAD> <input onkeypress='return capLock(event)' type='password' name='Password1' value='<?php if(!empty($Password1))echo $Password1;?>' /></td></tr> <tr><td> <em>*</em>Confirm Password</td><td><input type='password' name='Password2' value='<?php if(!empty($Password2))echo $Password2;?>' /></td></tr> <tr><td width="120"> <em>*</em>Enter Name</td> <td><input type='text' name='Name' value='<?php if(!empty($Name))echo $Name;?>' /></td></tr> <tr><td> <em>*</em>Enter Age</td><HEAD> <SCRIPT language=Javascript> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> </HEAD> <td><INPUT onkeypress='return isNumberKey(event)' type='text' name='Age' value='<?php if(!empty($Age))echo $Age;?>'/></td></tr> <tr><td> <em>*</em>Enter Blood</td><td><input type='text' name='BloodGroup' value='<?php if(!empty($BloodGroup))echo $BloodGroup;?>' /></td></tr> <tr><td> <em>*</em>Enter Sex</td><td><input type='radio' name='Sex' style='width:16px; border:0;' 'value='Male' />Male <input type='radio' name='Sex' style='width:16px; border:0;' 'value='Female' />Female</td></tr> <tr><td> <em>*</em>Enter Qualification</td><td><input type='text' name='Qualification' value='<?php if(!empty($Qualification))echo $Qualification;?>' /></td></tr> <tr><td> <em>*</em>Contact Number </td><td><input onkeypress='return isNumberKey(event)'type='text' name='ContactNumber' value='<?php if(!empty($ContactNumber))echo $ContactNumber;?>' /></td></tr> <tr><td> <em>*</em>Enter Email</td><td><input type='text' name='Email'class="email" value='<?php if(!empty($Email))echo $Email;?>' /></td></tr> <tr><td> <em>*</em>Enter Address</td><td><input type='text' name='Address' value='<?php if(!empty($Address))echo $Address;?>' /></td></tr> <tr ><td > <em>*</em>About Yourself </td></tr> <tr><td colspan="2"><textarea rows='10' cols='40' name='AboutYourself' /><?php if(!empty($Address))echo $Address;?></textarea></td></tr> <tr><td> <?php echo" <tr><td colspan='2'><em>*</em><b>Select fields for which you want to register</b></td></tr>"; require_once('database.php'); $query="select * from activity"; $result=mysqli_query($dbc,$query); while($row=mysqli_fetch_array($result)){ $Title=$row['Title']; $ActivityId=$row['ActivityId']; echo "<tr><td>$Title</td>"; echo "<td><input type='checkbox' name='checkbox[]' value='$Title' style='width:14px; text-align:right;'/></td></tr>";//value=$ActivityId tells ActivityId variable extracts with name="checkbox" echo "<br/>"; } echo "<td><em>*</em><input type='checkbox' name='TermsAndConditions' style='width:14px; text-align:right;'/></td><td> I agree all <a href='TermsAndConditions.php'>Terms and conditions </a>of Elite Brigade</td></tr>"; echo "<tr><td colspan='2' align='center'><input type='submit' value='Register' name='submit' style='background:url(./images/button_img2.png) no-repeat 10px 0px; width:100px; padding:3px 0 10px 0; color:#FEFBC4; border:0;'/></td></tr><br>"; echo " </td></tr></table> </div> </form> </body> </html>"; require_once('lower.php'); ?> Hi Friends .... I encrypt user password by SHA('$Password') method but now i want to add "Forget Password Module" for which I need to decrypt it first before tell my user but I don't Know how to decrypt it. Please help me........ Hi, My understanding of 'SHA' command is to encrypt the password, however is there a way to decrypt the password after the encryption? Thanks $query = "INSERT INTO mismatch_user (username, password, join_date) VALUES ('$username', SHA('$password1'), NOW())"; Alright, I've been assigned a project at work. I did not develop the application and the individual who did used CodeIgnited framework and mysql as the db.
Here's the problem, I'm not given much OT to do this and in our meeting the best way to proceed was to replicate the database for different parts of the organization. Basically we are a subsidiary and have been using an application that other groups within the organization want to use. Usually I would reconfigure the db schema and add org ids and in the user table add the appropriate organization to go to. However, they are not giving me enough time to do that.
So what I'm thinking is to just create a copy of the database we use (just the structure) and create a new database.
What I want to know is how to use mysql to check to see if a user exists in one database and if they don't then to go on to the next database. I understand this is a very sloppy way to do it, but it's the way we are moving forward.
I found the code to connect to the db in CodeIgnitor... how can I connect to a database, check to see if the user exists, then close that db connection and try the next database?
/** * Select the database * * @access private called by the base class * @return resource */ function db_select() { return @mysql_select_db($this->database, $this->conn_id); }Thanks in advance. I'm using this type of code below. how can my site may have access to my e-mail ? and how can I send e-mails containing passwords to users.?? please help. //code is like this// if($_POST['submit']=='Register') { // If the Register form has been submitted $err = array(); if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32) { $err[]='Your username must be between 3 and 32 characters!'; } if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username'])) { $err[]='Your username contains invalid characters!'; } if(!checkEmail($_POST['email'])) { $err[]='Your email is not valid!'; } if(!count($err)) { // If there are no errors $pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6); // Generate a random password $_POST['email'] = mysql_real_escape_string($_POST['email']); $_POST['username'] = mysql_real_escape_string($_POST['username']); // Escape the input data mysql_query(" INSERT INTO tz_members(usr,pass,email,regIP,dt) VALUES( '".$_POST['username']."', '".md5($pass)."', '".$_POST['email']."', '".$_SERVER['REMOTE_ADDR']."', NOW() )"); if(mysql_affected_rows($link)==1) { send_mail( 'myemail@xx.net', $_POST['email'], 'sitename - Your New Password', 'Your password is: '.$pass); $_SESSION['msg']['reg-success']='We sent you an email with your new password!'; } else $err[]='This username is already taken!'; } if(count($err)) { $_SESSION['msg']['reg-err'] = implode('<br />',$err); } header("Location: demo.php"); exit; } //but while running it on local server it shows the message "failure" as I have mentioned in the index.php. please provite a template codeing to solve the problem// hi i need help an idea how can i separate members from admins since i dont know how to create login form i used tutorial ( http://www.youtube.com/watch?v=4oSCuEtxRK8 ) (its session login form only that i made it work other tutorials wre too old or something) how what i want to do is separate members and admins because admin need more rights to do now i have idea but dont know will it work like that what i want to do is create additional row in table named it flag and create 0 (inactive user) 1 (member) 2 (admin) will that work? and how can i create different navigation bars for users and admins? do you recommend that i use different folders to create it or just script based on session and flag? I am createing a simply quiz site, where in order to participate in the quiz, you must first be logged in. While working on my local machine, the code works perfectly. I use the followin to create a session ID; $_SESSION['SESS_ID'] = $member['id']; Then, on my main page where i want dynamic code i include the following; if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID']) == '')) { print (" <div style='float:left; width:400px; height:215px; margin-left:500px;'> <form class='login' method='post' action='login-form.php' style='float:right; margin-top:120px;' > <input type='submit' class='button' name='submit' value='Sign In' style='float:right ; margin-right:20px;'> </form> <p style=' margin-top:170px; margin-left:160px;'>New Member? Start <a href='register-form.php'>Here</a></p> </div> " ); } else { print "<h4 style='float:right; text-align: right; margin-top:150px; margin-right:50px;'>Welcome ". $_SESSION['SESS_NAME']. " <a href='logout.php' style='float:right; text-align:right;'>Sign Out</a></h4> "; For some reason, when the site is on the server, the session ID does not seam to get passed along. Any Ideas how to remediy this? the website is kingdomquiz.com if anybody is interested. I am looking for a Script 1- which has a new user registeration and lhe can log to the site after "ADMIN APROVAL" 2- Multiple levles ie, user had multiple levles under which he can register on registration page ( Paid,Trial or Free) and after aproval of their registration by admin they r redirected to thier respective area ie free page, paid page or Trial page Thnks to all Seniour for Earilier help Hey there,
First time using MySQL database to connect to a member login. I have a paid subscription site through ccbill which they add the username and logins to. I have setup a database, username and password as well as a table that I have connected correctly "I believe" to my website but get this message: warning: MySQL-fetch_array()expects parameter 1 to be resource, Boolean given in /home....
My table I have setup just has username and password to authenticate the users, which I was told by ccbill is all I need. Maybe I need authentication 1 or 0 etc.
Any help on this would be amazing. Spent hours trying to figure this out but nothing.
Thanks for your time.
Steven
Hello everyone, I am trying to have a function on my website where the administrator can add a new member to the database. Their details are to be stored in the table memberdetails, I have posted the code below, the error i recieve is "Error: Column count doesn't match value count at row 1" Can anybody help me please? form code: <form action="insert.php" method="post"> Username: <input type="text" name="username" /><br><br> Firstname: <input type="text" name="firstname" /><br><br> Surname : <input type="text" name="surname" /><br><br> Date Birth: <input type="text" name="dob" /><br><br> Total Wins: <input type="text" name="wins" /> Total Loses: <input type="text" name="loses" /><br><br> Email Add: <input type="text" name="email" /><br><br> Country : <input type="text" name="born" /><br><br> Other Info: <input type="text" name="other" /><br><br> <input type="submit" name="Submit" value="Create" align="right"></td> </form> insert.php <?php mysql_connect ("localhost","root","") or die("Cannot connect to Database"); mysql_select_db ("test"); $sql="INSERT INTO memberdetails (username, firstname, surname, dob, totalwins, totalloses, email, country, info) VALUES ('$_POST[username]''$_POST[firstname]','$_POST[surname]','$_POST[wins]''$_POST[loses]''$_POST[email]''$_POST[born]''$_POST[other]''$_POST[dob]')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } echo "1 record added"; ?> I have a register page that MD5 Hash's the users password and a login which also does this. However, no matter what I try it always says incorrect password. Even when I remove the MD5. Register Code: Code: [Select] <?php error_reporting (E_ALL ^ E_NOTICE); ?> <!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>Member System - Register</title> </head> <body> <?php if ( $_POST['registerbtn'] ){ $getuser = $_POST['user']; $getemail = $_POST['email']; $getpass = $_POST['pass']; $getretypepass = $_POST['retypepass']; if ($getuser){ if ($getemail){ if ($getpass){ if ($getretypepass){ if ( $getpass === $getretypepass ){ if ( (strlen($getemail) >= 7) && (strstr($getemail, "@")) && (strstr($getemail, ".")) ){ require("./connect.php"); $query = mysql_query("SELECT * FROM users WHERE username='$getuser'"); $numrows = mysql_num_rows($query); if ($numrows == 0){ $query = mysql_query("SELECT * FROM users WHERE email='$getemail'"); $numrows = mysql_num_rows($query); if ($numrows == 0){ $password = md5(md5("kjfiufj".$password."Fj56fj")); $date = date("F d, Y"); $code = md5(rand()); mysql_query("INSERT INTO users VALUES ( '', '$getuser', '$password', '$getemail', '0', '$code', '$date' )"); $query = mysql_query("SELECT * FROM users WHERE username='$getuser'"); $numrows = mysql_num_rows($query); if ($numrows == 1){ $site = "http://c3221281.web44.net/"; $webmaster = "Simon <admin@simon.com>"; $headers = "From: $webmaster"; $subject = "Activate Your Account"; $message = "Thanks for registering. Click the link below to activate your account.\n"; $message .= "$site/activate.php?user=$getuser&code=$code\n"; $message .= "You must activate your account to login."; if ( mail($getemail, $subject, $message, $headers) ){ $errormsg = "You have been registered. You must activate your account from the activation link sent to <b>$getemail</b>."; $getuser = ""; $getemail = ""; } else $errormsg = "An error has occueed. Your activation email was not sent."; } else $errormsg = "An error has occured. Your account was not created."; } else $errormsg = "There is already a user with that email."; } else $errormsg = "There is already a user with that username."; mysql_close(); } else $errormsg = "You must enter a valid email address to register."; } else $errormsg = "Your passwords did not match."; } else $errormsg = "You must retype your password to register."; } else $errormsg = "You must enter your password to register."; } else $errrosmg = "You must enter your email to register."; } else $errormsg = "You must enter your username to register."; } $form = "<form action='./register.php' method='post'> <table> <tr> <td></td> <td><font color='red'>$errormsg</font></td> </tr> <tr> <td>Username:</td> <td><input type='text' name='user' value='$getuser' /></td> </tr> <tr> <td>Email:</td> <td><input type='text' name='email' value='$getemail' /></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='pass' value='' /></td> </tr> <tr> <td>Retype:</td> <td><input type='password' name='retypepass' value='' /></td> </tr> <tr> <td></td> <td><input type='submit' name='registerbtn' value='Register' /></td> </tr> </table> </form>"; echo $form; ?> </body> </html> Login Code: Code: [Select] <?php error_reporting (E_ALL ^ E_NOTICE); session_start(); $userid = $_SESSION['userid']; $username = $_SESSION['username']; ?> <!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>Member System - Login</title> </head> <body> <?php if ($username && $userid){ echo "You are already logged in as <b>$username</b>. <a href='./member.php'>Click here</a> to go to the member page."; } else{ $form = "<form action='./login.php' method='post'> <table> <tr> <td>Username:</td> <td><input type='text' name='user' /></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='password' /></td> </tr> <tr> <td></td> <td><input type='submit' name='loginbtn' value='Login' /></td> </tr> <tr> <td><a href='./register.php'>Register</a></td> <td><a href='./forgotpass.php'>Forgot your password?</a></td> </tr> </table> </form>"; if ($_POST['loginbtn']){ $user = $_POST['user']; $password = $_POST['password']; if ($user){ if ($password){ require("connect.php"); $password = md5(md5("kjfiufj".$password."Fj56fj")); // make sure login info correct $query = mysql_query("SELECT * FROM users WHERE username='$user'"); $numrows = mysql_num_rows($query); if ($numrows == 1){ $row = mysql_fetch_assoc($query); $dbid = $row['id']; $dbuser = $row['username']; $dbpass = $row['password']; $dbactive = $row['active']; if ($password == $dbpass){ if ($dbactive == 1){ // set session info $_SESSION['userid'] = $dbid; $_SESSION['username'] = $dbuser; echo "You have been logged in as <b>$dbuser</b>. <a href='./member.php'>Click here</a> to go to the member page."; } else echo "You must activate your account to login. $form"; } else echo "You did not enter the correct password. $form"; } else echo "The username you entered was not found. $form"; mysql_close(); } else echo "You must enter your password. $form"; } else echo "You must enter your username. $form"; } else echo $form; } ?> </body> </html> Many thanks for your time and help, Hi all,
I have been reading in almost everywhere that we should not use our own custom login and password validations ( like regex etc.) but instead use the filter_var and filter_input built in functions provided by PHP 5 and above. However even after searching for more than an hour for with different search strings, I have not found even a single example that shows how we may validate for a username/login and password in a login form. Can someone be kind enough to provide a strong secure validations for username and login.
Additionally I would also like to clarify if the username and login fields in a Login form be manipulated in any manner to pose a security threat? I mean can a hacker craft a username/login or password in such a manner as to pose an injection or any other threat?
Thanks all.
(Main Objective) I need this login class to encrypt the password before it sends it to the database for login verification. (Alternative Solution) Force a login with just the username and captcha no password.. This is the original working script.. <? session_start(); include "config.php"; global $c; include "data.php"; global $config; require('funciones.php'); if ($_POST['username']) { session_start(); if($_POST['code']!=$_SESSION['string']){ header("Location: login.php?error=1"); } //Comprobacion del envio del nombre de usuario y password $username=uc($_POST['username']); $password=uc($_POST['password']); if ($password==NULL) { header("Location: login.php?error=2"); }else{ $query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error()); if(mysql_num_rows($query) == 0) { header("Location: login.php?error=3"); } else { $data = mysql_fetch_array($query); if($data['password'] != $password) { header("Location: login.php?error=4"); }else{ $query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error()); $row = mysql_fetch_array($query); $nicke=$row['username']; $passe=$row['password']; //90 day cookie setcookie("usNick",$nicke,time()+7776000); setcookie("usPass",$passe,time()+7776000); $lastlogdate=time(); $lastip = getRealIP(); $querybt = "UPDATE tb_users SET lastlogdate='$lastlogdate', lastiplog='$lastip' WHERE username='$nicke'"; mysql_query($querybt) or die(mysql_error()); header("Location: members.php"); // echo "Has sido logueado correctamente ".$_SESSION['s_username']." y puedes acceder al index.php."; // echo "<script>location.href='index.php';</script>"; ?> <META HTTP-EQUIV="REFRESH" CONTENT="0;URL=members.php"> <? } } } } ?> <div class="heading">Login</div><br /> <? if($_GET['error'] == 1) { print "<b>Error</b> - Wrong Captcha Code<br /><br/>"; } if($_GET['error'] == 2) { print "<b>Error</b> - Please supply a password<br /><br/>"; } if($_GET['error'] == 3) { print "<b>Error</b> - Invalid Username<br><br>"; } if($_GET['error'] == 4) { print "<b>Error</b> - Invalid Password<br /><br />"; } ?> <form action="login.php" method="post"> <table> <tr> <td class="midtext">Username:</td> <td> <input type="text" name="username" size="25" class="form" autocomplete="off"></td> </tr> <tr> <td class="midtext">Password:</td> <td> <input type="password" name="password" size="25" class="form" autocomplete="off"></td> </tr> <tr> <td class="midtext" valign="top">Security Code:</td> <td class="midtext"> <img src="image.php" onclick="this.src='image.php?newtime=' + (new Date()).getTime();">(Click to reload)<br /> <input type="text" name="code" size="17" maxlength="17" autocomplete="off" class="form"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Login" name="loginsubmit" class="form"></td> </tr> </table> </form> Let me know if you need any files... Hi. I have made a login script, but I would wan't to encrypt the password. I followed a tutorial and got this: login.php <?php $password = "secret"; echo $password; /* displays secret */ $password = sha1($password); echo $password; /* displays e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4 */ ?> <form action="validate.php" method="post"> <label for="username">Username</label> <input type="text" name="username" id="username" /> <br /> <label for="password">Password</label> <input type="password" name="password" id="password" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> <?php ?> validate.php <?php include "setup.php"; /* get the incoming ID and password hash */ $username=$_POST['username']; $password=$_POST['password']; $password=md5($password); // Encrypted Password /* establish a connection with the database */ $server = mysql_connect("$db_host", "$db_username","$db_password"); if (!$server) die(mysql_error()); mysql_select_db("$database"); /* SQL statement to query the database */ $query = "SELECT * FROM users WHERE Username = '$username' AND Password = '$password'"; /* query the database */ $result = mysql_query($query); /* Allow access if a matching record was found, else deny access. */ if (mysql_fetch_row($result)) echo "Access Granted: Welcome, $username!"; else echo "Access Denied: Invalid Credentials."; mysql_close($server); ?> Its the line $password=md5($password); // Encrypted Password that messes everything up. If I delete it and login, everything is fine, if I add it it says Code: [Select] Access Denied: Invalid Credentials I need help with this one! And if someone have time, give me some ideas how to make PHP scripts safer! Regards Worqy Hi guys I have a script which i've been playing around with thanks to Spiderwell: http://www.phpfreaks.com/forums/index.php?action=profile;u=35078 I have sort of merged it with another 'member managment' script which is working great. Now i can't seem to correctly create a login page to pass the hashed password using (sha1). Now all i want to do is verify the username and the (hashed) password according to the database and allow the user in. The script i am using to check login works fine without a hashed password in the database. But ideally i'd like to use a hashed form of password. Can somebody show me what change i need to make in this script below in order to pass a sha1 hashed password? I'm guessing it's a really small change from the examples i've seen online, but i just cant seem to get mine to work. :| Your help would be much appreciated. Login Page PHP: Code: [Select] <form name="login" method="post" action="check_login.php3"> <p><strong>Secured Area User Log-in</strong></p> <p>Username: <input name="bioname" type="text" id="bioname"></p> <p>Password: <input name="biopass" type="password" id="biopass"></p> <p> </p> <p><input type="submit" name="Submit" value="Login"></p> </form> Check Login Processor (which is the file i that needs the sha1 added somewhere i think) Code: [Select] <?php require_once('config.php3'); // Connect to the server and select the database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db")or die("Unable to select database"); // $loginusername = false; $loginpassword = false; $err = false; // default error message is empty // The username and password sent from login.php //the isset() basically means if its there get it, otherwise dont bother if (isset($_POST['bioname'])) $loginusername=$_POST['bioname']; if (isset($_POST['biopass']))$loginpassword=$_POST['biopass']; // if either isnt filled in, tell the user, a very basic bit of validation if (!$loginusername || !$loginpassword) $err = "please complete the form"; if (!$err) //if no error continue { //The following bit of coding protects from MySQL injection attacks $loginusername = stripslashes($loginusername); $loginpassword = stripslashes($loginpassword); $loginusername = mysql_real_escape_string($loginusername); $loginpassword = mysql_real_escape_string($loginpassword); //you could add other things like check for text only blah blah $sql="SELECT * FROM $tbl WHERE bioname='$loginusername' and biopass='$loginpassword'"; $result=mysql_query($sql); // Count how many results were pulled from the table $count=mysql_num_rows($result); // If the result equals 1, continue if($count==1) { session_start(); $_SESSION['user'] = $loginusername; // store session data //please see I have used a session variable that is generic not specific, otherwise you will have to make this page different for every user //that would be a pain in the ass, you don't need to have user1 or user2, its the value stored that relevant, not what the variable name is header("Location: {$loginusername}/index.php3"); } else { $err = "Wrong Username or Password"; } }// end login if statement if ($err) // show error message if there is one { echo $err; echo "<br>Please go back in your browser and try again"; } ?> The secure page: Code: [Select] <?php session_start(); $mypath = $_SERVER["REQUEST_URI"]; //echo $mypath; // for debugging //now we have the path lets see if the username is in that path, i.e. test2 is inside /something/test2/index.php //use the built in strpos() function, which returns position of the last occurance of the string you are looking for inside another string. //http://php.net/manual/en/function.strrpos.php if(strpos($mypath,"/".$_SESSION['user']."/"))//on testing it failed initially as username test is found in path /test2/ so i added the slashes to stop that. so /test/ doesnt get found in /test2/ { echo "congratulations you are the right person in the right place"; } else { session_destroy(); //kill the session, naughty person trying to come here header("Location: ../login.php3"); die();// stop page executing any further } ?> <html> <body> </body> </html> Thanks and i look forward to your replies. Hello: I wanted to see if I can make my password protected pages in my admin area, and the login form "more secure." I was told I should use MD5 / SALTING / HASHING to do this. I have tried some online tutorials, but am not understanding it, so I wanted to start from what I have and build upon it> This is my database table storing the myAdmins data (when I initially insert it into the database): Code: [Select] CREATE TABLE `myAdmins` ( `id` int(4) NOT NULL auto_increment, `myUserName` varchar(65) NOT NULL default '', `myPassword` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO myAdmins VALUES("1","abc","123"); This is the login form I use: Code: [Select] <?php include('../include/myConn.php'); include('include/myAdminNav.php'); session_start(); session_destroy(); $message=""; $Login=$_POST['Login']; if($Login){ $myUserName=$_POST['myUserName']; $myPassword=$_POST['myPassword']; $result=mysql_query("select * from myAdmins where myUserName='$myUserName' and myPassword='$myPassword'"); if(mysql_num_rows($result)!='0'){ session_register("myUserName"); header("location:a_Home.php"); exit; }else{ $message="<div class=\"myAdminLoginError\">Incorrect Username or Password</div>"; } } ?> <form id="form1" name="form1" method="post" action="<? echo $PHP_SELF; ?>"> <? echo $message; ?> Username: <input name="myUserName" type="text" id="myUserName" size="40" /> Password: <input name="myPassword" type="password" id="myPassword" size="40" /> <input name="Login" type="submit" id="Login" value="Login" /> </form> This is the code on top of each page I password protect: Code: [Select] <? session_start(); if(!session_is_registered(myUserName)){ header("location:Login.php"); } ?> Works well, but can it be "better"?? And, if I am allowing the admin to update his/her username or password, I do it this way: Code: [Select] <?php include('../include/myConn.php'); include('include/myCheckLogin.php'); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $myUserName = mysql_real_escape_string($_POST['myUserName']); $myPassword = mysql_real_escape_string($_POST['myPassword']); $sql = " UPDATE myAdmins SET myUserName = '$myUserName', myPassword = '$myPassword' "; mysql_query($sql) && mysql_affected_rows() ?> <?php } $query=mysql_query("SELECT * FROM myAdmins") or die("Could not get data from db: ".mysql_error()); while($result=mysql_fetch_array($query)) { $myUserName=$result['myUserName']; $myPassword=$result['myPassword']; } ?> <form method="post" action="<?php echo $PHP_SELF;?>"> <input type="hidden" name="POSTBACK" value="EDIT"> Username: <input type="text" size="60" maxlength="60" name="myUserName" value="<?php echo $myUserName; ?>"> Password: <input type="password" size="60" maxlength="60" name="myPassword" value="<?php echo $myPassword; ?>"> <input type="submit" value="Submit" /> </form> Should it be "better" .. ?? I don't seem to understand how to "encrypt" all of this to make it "stronger" .. Ideas? Improvements? Hi! I have read like crazy to find a tutorial on a login page without My_SQL. Anyway I am working on a easy login/logged out page with sessions. Here is the login page with tree users in an array.
The things that I need some hints to solve is, when clicking on login the error message don't show. Instead the script goes to the logged in page right away. And when you write the wrong password you get loged in anyway.
I am not sure how or if it's possible to write a varible to a file this way. But I tried and recived a parse error with the txt varible.
When searching for topics I get more confused with the My_SQL varibles. I am near a breaking point at cracking the first step on PHP, but need some advice.
<?php $page_title = 'Logged in'; //Dynamic title include('C:/wamp/www/PHP/includes/header.html'); ?> <?php session_start(); //A array for the sites users with passwords $users = array( 'Dexter'=>'meow1', 'Garfield'=>'meow2', 'Miro'=>'meow3' ); //A handle to save the varible users to file on a new line from the last entry $handle = fopen("newusers.txt, \n\r") $txt = $users; fclose($handle); if(isset($_GET['logout'])) { $_SESSION['username'] = ''; header('Location: ' . $_SERVER['PHP_SELF']); } if(isset($_POST['username'])) { if($users[$_POST['username']] == $_POST['password']) { $_SESSION['username'] = $_POST['username']; }else { echo "Something went wrong, Please try again"; } } ?> <?php echo "<h3>Login</h3>"; echo "<br />"; ?> <!--A legend form to login--> <fieldset><legend>Fill in your username and password</legend> <form name="login" action="777log.php" method="post"> Username: <br /> <input type="text" name="username" value="" /><br /> Password: <br /> <input type="password" name="password" value="" /><br /> <br /> <input type="submit" name="submit" value="Login" /> </fieldset> </form> <?php //Footer include file include('C:/wamp/www/PHP/includes/footer.html'); ?>The logged in page <?php //Header $page_title = 'Reading a file'; include('C:/wamp/www/PHP/includes/header.html'); ?> <?php session_start(); //Use an array forthe sites users $users = array( 'Dexter'=>'meow1', 'Garfield'=>'meow2', 'Miro'=>'meow3' ); // if(isset($_GET['logout'])) { $_SESSION['username'] = ''; echo "You are now loged out"; //The user is loged out and returned to the login page header('Location: ' . $_SERVER['PHP_SELF']); } if(isset($_POST['username'])) { //Something goes wrong here when login without any boxes filled if($users[$_POST['username']] == $_POST['password']) { $_SESSION['username'] = $_POST['username']; }else { echo "Something went wrong, Please try again"; $redirect = "Location: 777.php"; } } ?> <?php if($_SESSION['username']): ?> <p><h2>Welcome <?=$_SESSION['username']?></h2></p> <p align="right"><a href="777.php">Logga ut</a></p><?php endif; ?> <p>Today Ben&Jerrys Chunky Monkey is my favorite!</p> <?php //Footer include('C:/wamp/www/PHP/includes/footer.html'); ?> 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! When I set up MS SQL on my machine, for whatever reason I did not set up a UID or password. I can not get the php to connect with SQL because I do not have a UID and password on the db (which I know is not smart). I don't understand code enough to know how to manipulate this string below to remove the requirement. |