PHP - Best Way To Handle User Login
Hi all.
I'm new to PHP language and I'd like to know which is the best way to handle the user login. With cookies or with sessions? Do you know some example on the web that I could inspire on? I just know how to do it in both way, I just wanna know which is the best way and like to read some code written by a pro. Similar TutorialsI was wondering if there's any common method for user management. I'm not talking about basic stuff like DB management stuff I'm talking about registering new users with captcha, validating email addresses, password resets, etc. I can work all this stuff out by hand but it seems rather large and very repetitious so I was wondering if there's guides out there to develop this or a common script? I would appreciate your assistance, there are tons of login scripts and they work just fine. However I need my operators to login and then list their activities for the other operators who are logged in to see and if desired send their clients on the desired activity. I have the login working like a charm and the activities are listed just beautifully. How do I combine the two tables in the MySQL with PHP so the operator Logged in can only make changes to his listing but see the others. FIRST THE ONE script the member logges in here to the one table in MSQL: <?php session_start(); require_once('config.php'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } $login = clean($_POST['login']); $password = clean($_POST['password']); if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: login-form.php"); exit(); } $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"; $result=mysql_query($qry); if($result) { if(mysql_num_rows($result) == 1) { session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['member_id']; $_SESSION['SESS_FIRST_NAME'] = $member['firstname']; $_SESSION['SESS_LAST_NAME'] = $member['lastname']; session_write_close(); header("location: member-index.php"); exit(); }else { header("location: login-failed.php"); exit(); } }else { die("Query failed"); } ?> ................................................. ................................ Now I need the person who logged in to the table above to be able to make multiple entries to the table below <? $ID=$_POST['ID']; $title=$_POST['title']; $cost=$_POST['cost']; $activity=$_POST['activity']; $ayear=$_POST['aday']; $aday=$_POST['ayear']; $seats=$_POST['special']; $special=$_POST['seats']; mysql_connect("xxxxxx", "xxx350234427", "========") or die(mysql_error()); mysql_select_db("xxxx") or die(mysql_error()); mysql_query("INSERT INTO `activity` VALUES ('ID','$title', '$cost','$activity', '$aday', '$ayear', '$special', '$seats')"); Print "Your information has been successfully added to the database!" ?> Click <a href="member-profile.php">HERE</a> to return to the main menu <?php ?> Hi guys, Can anyone assist me. I am trying to create a login for admin and user (if user not a member click register link) below is my code: But whenever I enter the value as: Username: admin Password:123 - I got an error message "That user does not exist!" Any suggestion and help would be appreciated. Thanks. login.php <?php //Assigned varibale $error_msg as empty //$error_msg = ""; session_start(); $error_msg = ""; if (isset($_POST['submit'])) { if ($a_username = "admin" && $a_password = "123") { //Define $_POST from form text feilds $username = $_POST['username']; $password = $_POST['password']; //Add some stripslashes $username = stripslashes($username); $password = stripslashes($password); //Check if usernmae and password is good, if it is it will start session if ($username == $a_username && $password == $a_password) { session_start(); $_SESSION['session_logged'] = 'true'; $_SESSION['session_username'] = $username; //Redirect to admin page header("Location: admin_area.php"); } } $username = (isset($_POST['username'])) ? $_POST['username'] : ''; $password = (isset($_POST['password'])) ? $_POST['password'] : ''; if($username && $password) { $connect = mysql_connect("localhost", "root", "") or die ("Couldn't connect!"); mysql_select_db("friendsdb") or die ("Couldn't find the DB"); $query = mysql_query ("SELECT * FROM `user` WHERE username = '$username'"); $numrows = mysql_num_rows($query); if ($numrows != 0){ while ($row = mysql_fetch_array($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } //Check to see if they are match! if ($username == $dbusername && md5($password) == $dbpassword) { header ("Location: user_area.php"); $_SESSION['username'] = $username; } else $error_msg = "Incorrect password!"; //code of login }else $error_msg = "That user does not exist!"; //echo $numrows; } else $error_msg = "Please enter a username and password!"; } ?> <!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=iso-8859-1" /> <title>Login Page</title> </head> <body> <br /> <?php require "header.php"; ?><br /> <div align="center"> <table width="200" border="1"> <?php // If $error_msg not equal to emtpy then display error message if($error_msg!="") echo "<div id=\"error_message\"style=\"color:red; \">$error_msg</div><br />";?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <!--form action="login_a.php" method="post"--> Username: <input type="text" name="username" /><br /><br /> Password: <input type="password" name="password" /><br /><br /> <input type="submit" name = "submit" value="Log in" /> </form> <p> </p> Register a <a href="register.php">New User</a> </table> </div> </body> </html> Hallo everybody,
i have the following code.
but i get allways this error while the user exist in the database.
User not found!
what do i do wrong?
thank you very much for your help
Rafal
<html> <head> <?php $connection = mysql_connect("db.xyz.com", "username", "password") or die ("connection fehler"); mysql_select_db("db0123456789") or die ("database fehler"); $email = $_POST["inp_email"]; $pwd = $_POST["inp_pwd"]; if($email && $pwd) { $chkuser = mysql_query("SELECT email FROM gbook WHERE email = '($email)' "); $chkuserare = mysql_num_rows($chkuser); echo $email; echo $pwd; if ($chkuserare !=0) { $chkpwd = mysql_query("SELECT pwd FROM gbook WHERE email = '($email)' "); $pwddb = mysql_fetch_assoc($chkpwd); if ($pwd != $pwddb["pwd"]) { echo "password is wrong!"; } else { echo "login successed"; } } else { echo "User not found!"; } } else { echo "Pleas enter your email and password!"; } mysql_close($connection); ?> </head> <body> <form action="login.php" method="post"> Email <input type="text" name="inp_email"><br> Password <input type="text" name="inp_pwd"><br> <input type="submit" name="submit" value="login"> </form> </body> </html> Edited by rafal, 21 September 2014 - 04:33 PM. Hallo everybody,
the user is in the table, but i get error (user not found!).
thank you very much for your help
Rafal
<!DOCTYPE html> <html> <head> <title>index</title> <meta http-EQUIV="CONTENT-LANGUAGE" content="en"> <?php SESSION_START(); include("abc.php"); $link2 = mysqli_connect("$hoster", "$nameuser", "$password", "$basedata") or die ("connection error" . mysqli_error($link2)); $email = $_POST["inp_email"]; $pwd = $_POST["inp_pwd"]; if($email && $pwd) { $chkuser = mysqli_query("SELECT email FROM $table2 WHERE email = '$email' "); $chkuserare = mysqli_num_rows($chkuser); if ($chkuserare !=0) { $chkpwd = mysqli_query("SELECT pwd FROM $table2 WHERE email = '$email'"); $pwddb = mysqli_fetch_assoc($chkpwd); if (md5($pwd) != $pwddb["pwd"]) { echo "Password is wrong!"; } else { $_SESSION['username'] = $email; header ('Location:list.php'); } } else { echo "user not found!"; } } else { echo "enter your Email and Password!"; } mysqli_close($link2); ?> </head> <body style="font-family: arial;margin: 10; padding: 0" bgcolor="silver"> <font color="black"> <br> <form action="index.php" method="post"> <b>Login</b><br><br> <table width="100%"> <tr><td> Email:<br><input type="text" name="inp_email" style="width:98%; padding: 4px;"><br> Password:<br><input type="password" name="inp_pwd" style="width:98%; padding: 4px;"><br> <br> <input type="submit" name="submit" value="Login" style="width:100%; padding: 4px;"> </td></tr> </table> </form> </font> </body> </html> Hello can someone point me into the right direction? I've got this code: if ($userdata["user_level"] <> 1 ){ die(); } The above code works but now I want to give users with level 3 also acces but not the users having level 2. Anyone has an idea? Regards Richard Ok. I would like to be able to do this :: http://webdeveloper.50webs.com/js.login.htm in PHP and with a database. I know it may look like a simple login script, but I would like it to redirect to a specific URL based on each user. I.E. "http://example.com/users/index.php" is the login page, and once the user logs in, it would redirect them to "http://example.com/users/username/" Unless someone has a better idea. I know this isn't secure (because someone could just change the url to a different username, and they now have access to that users account.) The only reason I would like to do it this way, is because I have an upload script, and because of the way it uploads, the files are placed in a folder (So username/files is were the files are stored) and I have a file browser (username/browser.php) And I don't know how to display only the files the user has uploaded. (I.E. if I had one main file that the users see once they login, they would all see everyones uploads.) I would forfeit a tiny bit of security if users had there files not publicly visible. (People still have to login to see the files, and they would have to know the URL to a specific username.) So basically what I would like to do, is have a database (I.E. "Users") and have a table in that database with "username" "password" "email" "URL" and the PHP script looks up the database, and checks the username, and the password, and if they match, looks at the URL and sees were its supposed to redirect the user. I have attached the PHP code I have found, and use. If anyone knows how to do this, please let me know! Thanks in advance! Cheers! ------ Anders
Hello, I am having trouble finding a tutorial on how to have a login system like facebook and many other sites where when you login you get taken to your own profile with your own information using PHP and Mysql. Any help would be much appreciated. Thanks I have a question for some more advanced developers out there. I am creating a user login class that I want to make secure. Now without cookies, no problem but everyone wants a remember me . So what I was planning on doing was storing a single unique value in a cookie. Now when the user visits the page it will check there unique value against the values in the database. Then what I wanted to do was have some other data that is unique to that user to see if they are the same person or not. For example when user A with ip address 0.0.0.0 goes to access my page and has a cookie stored it will check the database for user with ip address 0.0.0.0 and the unique value in there cookie. Now my question is, what values should I check against. It is my understanding that users can spoof ip addresses so that isnt exactly the best check. I was also going to use the hostname as well but you have to have the right ip address in order to check it so that isnt really reliable either. Another option is securing it another way. If anyone has any other suggestions that are secure to do a user login please let me know. I am open to anything at this point because I am creating the system from scratch. However, only secure systems are the way I want to go. I have advanced experience in php so dont worry about me not understanding . Any help is appreciated. Hey guys, How do I check to see if the user has been login on the page that they are on? I have a login and I want users to login before then can go to other pages. thanks guys, I am coding a php website and i have everything ready to start on the user interface, but now it wont get the data from the login to get data from the database. I added some debugging code in to see if it even gets a session and it doesn't even get one, can someone please help me and tell me what i am doing wrong?. My login code: Code: [Select] <?php include('/home/sites/******/MasterConfig/Config.php'); $tbl_name='U_members'; // Table name </p> session_start(); ob_start(); // Connect to server and select databse. mysql_select_db("$db_name")or die("cannot select DB"); // Define $myusername and $mypassword $myusername=$_POST['MYusername']; $rawpassword=$_POST['MYpassword']; $mypassword=md5($rawpassword); // 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"); $_SESSION['loggedin'] = true; $_SESSION['username'] = $_POST['MYusername']; header("location:/welcome.php"); } else { echo "Wrong Username or Password"; } ob_end_flush(); ?> Welcome.php: Code: [Select] <?php include('/home/sites/*********MasterConfig/Config.php'); $tbl_name = "U_items"; // Table name </p> ob_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <?php ob_start(); session_start(); ?> <meta charset="utf-8"> <link rel="stylesheet" href="css/all.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.easing.1.3.js"></script> <script type="text/javascript" src="js/jquery.quicksand.js"></script> <script type="text/javascript" src="js/main.js"></script> <title>Product Filter</title> </head> <body> <?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) { } else { mysql_close($_SESSION['connect']); header("location:/index.php"); } ?> <h1> Welcome <?php $_SESSION['username']; ?> </h1> <div id="container"> <ul id="filterOptions"> <li class="active"><a href="#" class="all">All my products</a></li> <li><a href="#" class="Car">My cars</a></li> <li><a href="#" class="champ">My motorbikes</a></li> <li><a href="#" class="league1">My ECO</a></li> <li><a href="#" class="league2">My Art</a></li> </ul> <ul class="ourHolder"> <li class="item" data-id="id-1" data-type="Car"> <?php mysql_select_db("$db_name")or die("cannot select DB"); $SQL = mysql_query('SELECT * FROM ' + $tbl_name + ' WHERE Owner = ' + $_SESSION['username']); while($row = mysql_fetch_row($SQL)); $id=$row['ID']; $photo=$row['PicLink']; $ItemName=$row['Name']; if(isset($_SESSION['userName'])) { print "Your session username: ".$_SESSION['username']. "<br>"; } else { print "Session does not exist"; } ?> <img src="<?php $Photo ?>" alt="<?php $ItemName ?>" /> <h3> <?php $ItemName ?></h3> </li> </li> </ul> </div> </body> </html> i try to create login page with two different user level for example admin and staff. i did not get any error on my code but it just did not direct to the page it been set to. it just display wrong username or password. i not really sure what is wrong. here is the code loginForm.php Code: [Select] <form action="login.php" method ="post"> <table> <tr><td>Usernama</td> <td><input name="username" type="text" size = "15" maxlength = "15"/></td></tr> <tr><td>Password</td> <td><input name="password" type="password" size = "15" maxlength = "15"/></td></tr> </table> <br><input name="submit" type ="submit" value ="Login"/></td> </form> login.php Code: [Select] <?php ob_start(); $host="localhost"; $user="root"; $pass=""; $db_name="office"; $tbl_name="login"; mysql_connect("$host", "$user", "$pass")or die("cannot connect"); mysql_select_db("$db_name")or die("Cannot Select Database"); // username and password sent from form $sername=$_POST['username']; $password=$_POST['password']; $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM daftarPenyelia WHERE user='$username' AND pass='$password' AND userLevel='$userLevel'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); if ($count == $userLevel) { if ($userLevel == 1) { $_SESSION['username'] = $username; $_SESSION['password'] = $password; header("location:adminMenu.php"); } else if ($userLevel == 2) { $_SESSION['username'] = $username; $_SESSION['password'] = $password; header("location:staffMenu.php"); } } else { echo "Wrong Username or Password"; } ?> can someone help me with this code and tell me what is wrong so that i can fix them This topic has been moved to PHP Freelancing. http://www.phpfreaks.com/forums/index.php?topic=330064.0 Hey guys, I have an issue with my php code. After registering in my site, i (the user) can't login again. It displays a message: Quote The email and password combination you entered is incorrect. Code: [Select] <?php if(logged_in()) { $user_data = user_data('name'); echo 'Welcome, ', $user_data['name']; } else { ?> <form action="" method="post" > <p> Email: <input type="email" name="login_email" /> Password: <input type="password" name="login_password" /> <input type="submit" value="Log in" /> </p> </form> <?php } if (isset($_POST['login_email'], $_POST['login_password'])) { $login_email = $_POST['login_email']; $login_password = $_POST['login_password']; $errors = array(); if(empty($login_email) || empty($login_password)){ $errors[] = 'Email and password are required!'; } else { $login = login_check($login_email, $login_password); if($login === false) { $errors[] = 'The email and password combination you entered is incorrect.'; } } if(!empty($errors)) { foreach ($errors as $error) { echo $error. '<br />'; } } else { $_SESSION['user_id'] = $login; header('Location: index.php'); exit(); } } ?> And here's the function where I call check the login: Code: [Select] <?php function login_check($email, $password) { $email = mysql_escape_string($email); $login_query = mysql_query("SELECT COUNT(`user_id`) as `count`, `user_id` FROM `users` WHERE `email`='$email' AND `password`='".md5($password) ."'"); return(mysql_result($login_query, 0) == 1) ? mysql_result($login_query, 0, 'user_id') : false; echo mysql_error(); } ?> Any clue of what this could be? Hi, I would like to make a login page with 2 different user level, Admin & Staff. How can i do it using d code below. Thank u. <?php $host="localhost"; $username="root"; $password=""; $db_name="profile"; $tbl_name="company"; mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("Cannot Select Database"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; $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($count==1){ session_register("myusername"); session_register("mypassword"); header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> i have homework about this but i don't know how to make it work, after a few hours it stuck with every login will go to same place i must create 4 id : 1.owner : can access all page , edit all id 2.chasier : report any item out, only access item out page (item.php) 3.warehouse : add item from purchasing department, add new item, get notification from chasier, tell purchasing department to buy item 4.purchasing department : get notification from warehouse, sent report to warehouse after add stock or add new item login.php Code: [Select] <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="form1" method="post" action="cek_login.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td colspan="3"><strong>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="text" id="password"></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Login"></td> </tr> </table> </td> </form> </tr> </table> cek_login.php Code: [Select] <?php $host="localhost"; $username="root"; $password=""; $db_name="shop_system"; $tbl_name="members"; mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $username=$_POST['username']; $password=$_POST['password']; $usertype=$_GET['usertype']; $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password' "; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_register("username"); session_register("password"); header("location:sukses.php"); } else { echo "Wrong Username or Password"; } ?> sukses.php Code: [Select] <? session_start(); if(!session_is_registered(myusername)){ header("location:main_login.php"); } ?> <html> <body> Login Successful </body> </html> Hi All, I have currently been working on a login/registration system for a university project and I am now struggling with the login section. The problem is with one particular function and an if statement. The function checks to see if the username and password entered matches the username and password in the database but each time I get it echoing username/password incorrect. the function is Code: [Select] function valid_credentials($user, $pass) { $user = mysql_real_escape_string($user); $pass = sha1($pass); $total = mysql_query("SELECT COUNT(`user_username`) FROM `users` WHERE `user_username` = '{$user}' AND `user_password` = '{$pass}'"); return (mysql_result($total, 0) == '1') ? true : false; } and the statement is Code: [Select] if (valid_credentials($_POST['username'], $_POST['password']) == false) { $errors = 'Username/Password incorrect.'; } Any help would be greatly appreciated as this has been bugging me for the past 5 days :/ I'm trying to make a simple but secure login/user registration for this site I'm building. I'm new to php, so I followed some tutorials from www.newthinktank.com. http://www.newthinktank.com/2011/01/php-security-pt-2/ http://www.newthinktank.com/2011/01/php-security-pt-4-set-up-captcha// http://www.newthinktank.com/2011/01/web-design-and-programming-pt-21-secure-login-script/ But I'm having a couple of problems. On the registration.php file, whenever I type in wrong information, the validation error messages don't display and also whenever I click the submit button, the form doesn't do anything. It doesn't insert information into my database. It just shows the empty form. On my login.php file, again the validation errors don't display and I can't tell if I'm logged in or not. The form redirects to my index page, but the user box that shows the different menus depending on whether or not someone is logged in stays in guest mode. I don't get any php error messages on either file. Here's my code: register.php file: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled</title> <link href="_css/page_layout.css" rel="stylesheet" type="text/css" /> <link href="_css/page_text.css" rel="stylesheet" type="text/css" /> <link href="_css/sidebarLeft.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrapper"> <?php include('_includes/template/header.php'); ?> <?php include('_includes/template/nav.php'); ?> <?php include('_includes/template/sidebar_left.php'); ?> <div id="mainContent"> <div class="content"> <?php require_once('_includes/connectvars.php'); if (isset($_POST['submitted'])) { if (preg_match ('%^[A-Za-z\.\' \-]{2,20}$%', stripslashes(trim($_POST['first_name'])))) { $firstname = escape_data($_POST['first_name']); } else { $firstname = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid first name!</font></p>'; } if (preg_match ('%^[A-Za-z\.\' \-]{2,40}$%', stripslashes(trim($_POST['last_name'])))) { $lastname = escape_data($_POST['last_name']); } else { $lastname = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid last name!</font></p>'; } if (preg_match ('%^(0?[1-9]|[12][0-9]|3[01])[-/. ](0?[1-9]|1[0-2])[-/.](19|20)\d{2}$%', stripslashes(trim($_POST['birth_date'])))) { $birthdate = escape_data($_POST['birth_date']); } else { $birthdate = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid date of birth!</font></p>'; } $gender = escape_data($_POST['gender']); if (preg_match ('%^[0-9]{5}$%', stripslashes(trim($_POST['zip_code'])))) { $zipcode = escape_data($_POST['zip_code']); } else { $zipcode = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid 5 digit zip code!</font></p>'; } if (preg_match ('%^[A-Za-z0-9._\%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$%', stripslashes(trim($_POST['email'])))) { $email = escape_data($_POST['email']); } else { $email = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid email address!</font></p>'; } if (preg_match ('%^[a-z\d_]{2,20}$%', stripslashes(trim($_POST['username'])))) { $username = escape_data($_POST['username']); } else { $username = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid username!</font></p>'; } if (preg_match ('%\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{6,}\z%', stripslashes(trim($_POST['password1'])))) { if (($_POST['password1'] == $_POST['password2']) && ($_POST['password1'] != $_POST['username'])) { $password = escape_data($_POST['password1']); } elseif ($_POST['password1'] == $_POST['username']) { $password = FALSE; echo '<p><font color="red" size="+1″>Your password cannot be the same as the username!</font></p>'; } else { $password = FALSE; echo '<p><font color="red" size="+1″>Your password did not match the confirmed password!</font></p>'; } } else { $password = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid password!</font></p>'; } $captchchk = 1; require_once('_includes/recaptchalib.php'); $privatekey = "My private key goes here...i know"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { echo '<p><font color="red" size="+1″>The CAPTCHA Code wasn\'t entered correctly! </font></p>'; $captchchk = 0; } if ($firstname && $lastname && $birthdate && $gender && $zipcode && $email && $username && $password) { $query = "SELECT user_id FROM users WHERE username='$username'"; $result = mysql_query($query) or trigger_error("Sorry, that username is taken"); if(mysql_num_rows($result) == 0) { $a = md5(uniqid(rand(), true)); $query = "INSERT INTO users(zip_code, username, first_name, password, activation_code, join_date, last_name, gender, birth_date, email) VALUES ('$zipcode', '$username', '$firstname', SHA('$password'), '$a', NOW(), '$lastname', '$gender', '$birthdate', '$email')"; $result = mysql_query($query) or trigger_error("Sorry an error happened"); if(mysql_affected_rows() == 1) { $body = "Thanks for registering. Activate account by clicking this link: <br />"; $body .= "http://localhost/activate.php?x=" . mysql_insert_id() . "&y=$activationcode"; mail($email, 'Registration Confirmation', '$body', 'From: admin@mysite.com'); echo '<br /><br /><h1>Thank you for registering! A confirmation email has been sent to your address. Please click on the link in that email in order to activate your account.</h1>'; } exit(); } else { echo '<p><font color="red" size="+1″>You could not be registered due to a system error. We apologize for any inconvenience.</font></p>'; } } else { echo '<p><font color="red" size="+1″>That email address has already been registered. If you have forgotten your password, use the link to have your password sent to you.</font></p>'; } mysql_close(); } ?> <h1>Register</h1> <br /> <p>Please fill out the form below. All fields required.</p> <br /> <center><form action="register.php" method="POST" id="regform"> <table width="550" border="0"> <tr> <td width="200"><p>First Name:</p></td> <td width="200"><label for="first_name"></label> <input name="first_name" type="text" id="first_name" maxlength="20" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/></td> <td width="200"> </td> </tr> <tr> <td><p>Last Name:</p></td> <td><label for="last_name"></label> <input name="last_name" type="text" id="last_name" maxlength="45" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Birthdate:</p></td> <td><label for="birth_date"></label> <input name="birth_date" type="text" id="birth_date" maxlength="10" value="<?php if (isset($_POST['birth_date'])) echo $_POST['birth_date']; ?>"/></td> <td><p>(Format: MM/DD/YYYY)</p></td> </tr> <tr> <td><p>Gender</p></td> <td><p> <label> <input type="radio" name="gender" value="F" id="gender_0" /> F </label> <label> <input type="radio" name="gender" value="M" id="gender_1" /> M </label> <input name="gender" type="hidden" value="" /> <br /> </p></td> <td> </td> </tr> <tr> <td><p>Zip Code</p></td> <td><label for="zip_code"></label> <input name="zip_code" type="text" id="zip_code" maxlength="5" value="<?php if (isset($_POST['zip_code'])) echo $_POST['zip_code']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Email:</p></td> <td><label for="email"></label> <input name="email" type="text" id="email" maxlength="255" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Username:</p></td> <td><label for="username"></label> <input name="username" type="text" id="username" maxlength="60" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>"/></td> <td> </td> </tr> <tr> <td><p>Choose New Password:</p></td> <td><label for="password1"></label> <input name="password1" type="password" id="password1" maxlength="40" /></td> <td> </td> </tr> <tr> <td><p>Confirm New Password:</p></td> <td><label for="password2"></label> <input name="password2" type="password" id="password2" maxlength="40" /></td> <td> </td> </tr> </table> </br> <?php require_once('_includes/recaptchalib.php'); $publickey = "my public key goes here...i know"; // you got this from the signup page echo recaptcha_get_html($publickey); ?> <br /> <input type="submit" name="submit_signup" id="submit_signup" value="Sign Up" /> <input type="hidden" name="submitted" value="TRUE" /> </form></center> <br /> <br /> </div> </div> <?php include('_includes/template/sidebar_right.php'); ?> <?php include('_includes/template/footer.php'); ?> </div> </body> </html> login.php file: Code: [Select] <?php session_start(); require_once('_includes/connectvars.php'); ?> <?php if (isset($_POST['submitLogin'])) { if (preg_match ('%^[A-Za-z0-9]\S{6,20}$%', stripslashes(trim($_POST['username'])))) { $username = escape_data($_POST['username']); } else { $username = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid username!</font></p>'; } if (preg_match ('%^[A-Za-z0-9]\S{6,20}$%', stripslashes(trim($_POST['password'])))) { $password = escape_data($_POST['password']); } else { $password = FALSE; echo '<p><font color="red" size="+1″>Please enter a valid password!</font></p>'; } if ($username && $password) { $query = "SELECT user_id, level_access, username, password, join_date, first_name, last_name, birth_date, gender, zip_code, email, activation_code FROM users WHERE username='$username' AND password=SHA('$password')"; $result = mysql_query ($query) or trigger_error("Either the Username or Password are incorrect"); if (mysql_affected_rows() == 1) { $row = mysql_fetch_array ($result, MYSQL_NUM); mysql_free_result($result); $_SESSION['first_name'] = $row[5]; $_SESSION['username'] = $row[2]; $tokenId = rand(10000, 9999999); $query2 = "update users set tokenid = $tokenId where username = '$_SESSION[username]'"; $result2 = mysql_query ($query2); $_SESSION['token_id'] = $tokenId; session_regenerate_id(); header("Location: http://localhost/mysite/index.php"); mysql_close(); exit(); } } else { echo '<br><br><p><font color="red" size="+1″>Either the Username or Password are incorrect</font></p>'; mysql_close(); exit(); } echo '<br><br><p><font color="red" size="+1″>Either the Userid or Password are incorrect</font></p>'; mysql_close(); exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled</title> <link href="_css/page_layout.css" rel="stylesheet" type="text/css" /> <link href="_css/page_text.css" rel="stylesheet" type="text/css" /> <link href="_css/sidebarLeft.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrapper"> <?php include('_includes/template/header.php'); ?> <?php include('_includes/template/nav.php'); ?> <?php include('_includes/template/sidebar_left.php'); ?> <div id="mainContent"> <div class="content"> <h1>Login</h1> <form action="login.php" method="post" name="login" id="login"> <table width="200" border="0"> <tr> <td><p>Username:</p></td> <td><label for="username"></label> <input type="text" name="username" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>"/></td> </tr> <tr> <td><p>Password:</p></td> <td><label for="password"></label> <input type="password" name="password" id="password" /></td> </tr> </table> <br /> <p> <label> <input type="radio" name="remember_me" value="radio" id="remember_me_0" /> Keep me logged in </label> <br /> </p> <br /> <input type="submit" name="submitLogin" value="Login" /> <input type="hidden" name="submitted" value="TRUE" /> </form> <br /> <p>Not a member? <a href="register.php">Create an account!</a></p> <br /> <p>Forgot password?</p> </div> </div> <?php include('_includes/template/sidebar_right.php'); ?> <?php include('_includes/template/footer.php'); ?> </div> </body> </html> Here's the code that shows the different menus depending on if someone is logged in or not. Code: [Select] <div class="login"> <?php echo '<p>'; echo 'Welcome '; if (isset($_SESSION['first_name'])) { echo " {$_SESSION['first_name']}!</br></br>"; } else { echo 'Guest!'; } if (isset($_SESSION['username']) AND (substr($_SERVER['PHP_SELF'], -10) != 'logout.php')) { echo '<a href="add_event.php">Add an Event</a></br> <a href="my_profile.php">My Profile</a></br> <a href="logout.php"><p>Logout</a></br>'; } else { echo '</br> <a href="register.php">Register</a></br> <a href="login.php">Login</a></br>'; } echo'</p>'; ?> </div> I would like to know how to take details of my 'users' table from mysql database and check if that user is logged in using cookies or sessions somehow and have that users username displayed on my site, something like: user logged in as: (username), how is this done? What would you guys need to see in order for you to help me? im guessing the login and register scripts which are below, if you need anymore let me know, thanks. Login script: Code: [Select] <?php if(isset($_POST['submit'])){ //check for submit button click $username = $_POST['myusername']; $password = $_POST['mypassword']; // proceed with rest of code $self = $_SERVER['PHP_SELF']; $referer = $_SERVER['HTTP_REFERER']; #if either form field is empty return to the log-in page if( (!$username ) or (!$password ) ) { header( "Location:$referer" ); exit(); } #connect to mysql $conn = @mysql_connect( "myserver", "username", "password" ) or die( "Could not connect" ); #select database $rs = @mysql_select_db( "removalspacelogin", $conn ) or die ( "Could not select db" ); #create query $sql="select * from users where username = '$username' and upassword = '$password'"; #execute query $rs = mysql_query( $sql, $conn ) or die( mysql_error() ); #get number of rows that match username and password $num = mysql_numrows( $rs ); #if there is a match the log-in is done if( $num != 0 ) { header( "Location:login_success.php" ); } else #or return to: login.php { header( "Location:$referer" ); exit(); } } ?> <?php ini_set("display_errors","ON"); ?> <html> <head><title>Check-login</title></head> <body> <?php echo( $msg ); ?> </body> </html> Register users script: Code: [Select] <?PHP $user_name = "removalspace"; $password = "123"; $database = "removalspacelogin"; $server = "removalspacecom.ipagemysql.com"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO users (username, upassword, email) VALUES ('" .$username. "', '" .$upassword. "', '" .$email. "')"; $result = mysql_query($SQL); header( 'Location: http://www.removalspace.com/index.php' ); exit(); } else { print "Database NOT Found "; mysql_close($db_handle); } ?> |