PHP - Login Script And Sessions Error
Similar TutorialsIf you are a PHP expert, then I really your help. I have a question regarding PHP sessions and their security. So here is my story ... I created a login script (login.php) for my website. When a user goes to the login.php page, they see a login form that they must fill with their username and password to login to the members' area and view their profile, etc. On that login page, when the user enters their username and password and then clicks the "Login" button, my script filters the data, sends MySQL query and checks if the login is valid. If the login is NOT valid, then they get a "Login Failed" message. If the login is valid, I register their username and the password in sessions and redirect them to the members.php page. Here is some of my code for my login.php page after mysql confirms the login is valid <?php $query = mysql_query('SELECT * FROM `users` WHERE username='$user' AND password='$pass'"); $numRows = mysql_num_rows($query); if ( $numRows ) { // login is valid $_SESSION['username'] = $user; $_SESSION['pass'] = $pass; // redirect user to members area header('Location: /members.php'); } else { // login is invalid echo "Login failed"; } ?> My question is ... is this login script secured? I mean, I am not generating any session id or any cookie. I am just storing the username and the password in two session variables and those are the things that i will use to display the user's profile, etc. Can attackers attack this script? Is this secured or is there any other way I can make it stronger? Hi, Im using the code below to check a users username and password is ligit before adding their username to their session. <?php $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("hiddenbid", $con); $username = mysql_real_escape_string($_POST['username']); $password = md5($_POST['password']); $mysql = mysql_query("SELECT * FROM users WHERE name = '{$username}' AND password = '{$password}'"); if(mysql_num_rows($mysql)=1){ $_SESSION['USERID'] = $username; print "<b>Welcome</b>, you are signed in as " . $_SESSION['USERID'] . "."; print "<br /><br />Redirecting..."; header ("location:index.php"); } else{ header ("location:signin.php"); } ?> Anyway, it doesnt work as I get the following error: Fatal error: Can't use function return value in write context in C:\Program Files\Abyss Web Server\htdocs\signinconfirmer.php on line 35 Any ideas what is causing this please? Also can I add a pause after the redirect message before it takes the user to the index.php page? Thanks in advance. Hi all, I've got a website, which used to work ... I have a login script which did log each user in fine, but now for some odd reason its not loggin them in, I've looked over the script quite a few times but carnt see why its not loggin then it as it use to. <?php session_start(); include_once"includes/config.php"; if (strip_tags($_GET['logout']) == "yes"){ session_destroy(); }elseif (isset($_SESSION['username'])){ header("Location: index2.php"); exit(); } if ($_POST['Submit'] && strip_tags($_POST['username']) && strip_tags($_POST['password'])){ $username = mysql_real_escape_string(addslashes(strip_tags($_POST['username']))); $password = md5(addslashes(strip_tags($_POST['password']))); $select = mysql_query("SELECT * FROM users WHERE online > '$timenow' ORDER by rank desc"); $num = mysql_num_rows($select); $date = gmdate('Y-m-d h:i:s'); $ip = $REMOTE_ADDR; ///check INFO $sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1"); $login_check = mysql_num_rows($sql); $inf = mysql_fetch_object($sql); if ($login_check == "0"){ $message="<table width='30%' class='table' align='center' cellpadding='0' cellspacing='0' border='1'> <tr> <td class='header' align='center'>Error</td> </tr> <tr> <td align='center'>You could not be logged in.</td> </tr> <table><br />"; }elseif ($login_check != "0"){ if ($login_check > "0"){ if ($inf->status == "Banned"){ $encoded=md5(strtolower($username)); header("Location: banned.php?banned=$username&encoded=$encoded"); exit(); } session_register('username'); $_SESSION['username'] = $inf->username; $timestamp = time()+20; $get = mysql_query("SELECT * FROM users WHERE username='$username' LIMIT 1"); $got = mysql_fetch_object($get); $loginnumber = $got->loginnumber+1; mysql_query("UPDATE users SET online='$timestamp' WHERE username='$username'"); mysql_query("UPDATE users SET lastlogin='$date' WHERE username='$username'"); mysql_query("UPDATE users SET l_ip='$ip' WHERE username='$username'"); mysql_query("UPDATE users SET loginnumber='$loginnumber' WHERE username='$username'"); header("Location: index2.php"); } else { $message= "<table width='30%' class='table' align='center' cellpadding='0' cellspacing='0' border='1'> <tr> <td class='header' align='center'>Error</td> </tr> <tr> <td align='center'>You could not be logged in.</td> </tr> <table><br />"; }}} ?> <html> <head> <title>Login </title> <link href='style.css' rel='stylesheet' type='text/css'> </head> <body class='body'> <form action='' method='post' name='form1'> <?php echo ($message); ?> <table width='702' class='table' align='center' cellpadding='0' cellspacing='0' border='1'> <tr> <td class='header' align='center' colspan='2'>Welcome To Speed-Drive</td> </tr> <tr> <td align='center' colspan='2'><img src='images/banner.png'></td> </tr> <tr> <td class='header' align='center' colspan='2'>Speed-drive Login</td> </tr> <tr> <td width='50%' align='right'>Username:</td><td width='50%' align='left'><input name="username" class='input' type="text" maxlength="15" id="username"></td> </tr> <tr> <td width='50%' align='right'>Password:</td><td width='50%' align='left'><input name="password" class='input' type="password" maxlength="30" id="password"></td> </tr> <tr> <td colspan='2' align='center' class='omg'><input type="submit" class='button' name="Submit" value="Submit"></td> </tr> <tr> <td class='header' align='center' colspan='2'>Help</td> </tr> <tr> <td align='center' colspan='2'><a href='register.php'>Register</a> .|. <a href='lost.php'>Lost Password</a> .|. <a href='tos.php'>TOS</a></td> </tr> <tr> <td align='center' colspan='2'><br /><font color='pink'><strong><h3>This website is currently <u></font><font color='red'>closed</font><font color='pink'></u>!<br /><br />You will <u></font><font color='red'>Not</font><font color='pink'></u> be able to Register untill the website is completed.<br /><br /></font></h3> Thank you for understanding.</strong></td> </tr> </table> </form> </body> </html> Is there a small error in the script or is the Script fine? Thanks for all the help given. 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 Checking to see if I am going in the right direction, any suggestions would be appreciated! I am setting up SESSIONs for login and setting a time limit on them. I have basically 2 scenarios that I need to code for. 1. Registerd user w/good billing has all access 2. Registerd user w/expired billing & Guest user can only go to certain pages and have limited access This is my login page, will validate the login info and either sends user to one page or another or gives error that the login is incorrect <?php // http://www.daniweb.com/forums/thread124500.html session_start(); // starting session if( isset($_POST['submitLogin'])) { include('library/login.php'); login(); mysql_select_db('test'); // username and pswd from login $userID=$_POST["userID"]; $pswd=$_POST["pswd"]; // to protect from MySQL injection $userID = stripslashes($userID); $pswd = stripslashes($pswd); $userID = mysql_real_escape_string($userID); $pswd = mysql_real_escape_string($pswd); $sql="SELECT * FROM user WHERE userID='$userID' and pswd='$pswd'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $userID and $pswd, table row must be 1 row if($count == 1) { session_register("userID"); session_register("pswd"); $_SESSION['userID'] = $userID; // verifies billing if ($exp_date >= $todays_date) { // billing is up to date echo "<meta http-equiv='refresh' content='0;url=session2.php'>"; } else { // billing has expired echo "<meta http-equiv='refresh' content='0;url=expBilling.php'>"; } } else { // login form for when there us an incorrect user/password echo " <div id='incorrect'>Please verify the username or password.</div> <form method='post' action='' name='login' id='login'> <div id='loginForm'> <fieldset> <span class='textbox'> <label for='username'>Username: </label> <input type='text' name='userID' size='25' class='cells' value='$userID'> <br><label for='pswd'>Password: </label> <input type='password' name='pswd' size='25'class='cells' value='$pswd'> <br><label for='pswd'> </label>Remember Me: <input type='checkbox' name='Remember' value='21'> <br><label for='blank'> </label><a href='resetPswd.php'>Forget Your Password? </a> <br><label for='blank'> </label><input type='image' value='Login' src='img/button_login.gif' width='64' height='25' onmouseover=\"javascript:this.src='img/button_login2.gif';\" onmouseout=\"javascript:this.src='img/button_login.gif';\"> <input type='hidden' name='submitLogin' value='true'> </span> </fieldset> </div> </form> "; } } else { // log in form echo " <form method='post' action='' name='login' id='login'> <div id='loginForm'> <fieldset> <span class='textbox'> <label for='username'>Username: </label> <input type='text' name='userID' size='25' class='cells'> <br><label for='pswd'>Password: </label> <input type='password' name='pswd' size='25'class='cells'> <br><label for='pswd'> </label>Remember Me: <input type='checkbox' name='Remember' value='21'> <br><label for='blank'> </label><a href='resetPswd.php'>Forget Your Password?</a> <br><label for='blank'> </label><input type='image' value='Login' src='img/button_login.gif' width='65' height='25' onmouseover=\"javascript:this.src='img/button_login2.gif';\" onmouseout=\"javascript:this.src='img/button_login.gif';\"> <input type='hidden' name='submitLogin' value='true'> </span> </fieldset> </div> </form> "; } ?> If the billing is good then user will go here <?PHP session_start(); // session timing // set timeout period in seconds $inactive = 15; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing if(!session_is_registered(userID)){ header("location:login.php"); } ?> <html> <body> Login Successful </body> </html> If the billing has expired user goes here <?php session_start(); // session timing // set timeout period in seconds $inactive = 15; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing // if the user has been timed out or not logged in if(!session_is_registered(userID)){ header("location:form.php"); } // user is logged in and their billing is good else { echo "Warning! <b>"; echo $_SESSION['userID']; echo "</b> Your billing has expired "; } // end session ?> I also created this page to test what happens when a non-subscriber trys to go to a page without logging in, it also test the billing and blocks a user whose billing is expired. <?php session_start(); // session timing // set timeout period in seconds $inactive = 15; // check to see if $_SESSION['timeout'] is set if(isset($_SESSION['timeout']) ) { $session_life = time() - $_SESSION['timeout']; if($session_life > $inactive) { session_destroy(); } } $_SESSION['timeout'] = time(); // END session timing // if the user has been timed out or not logged in if(session_is_registered(userID)){ // verify billing if user comes in directly thru this page include('library/login.php'); login(); mysql_select_db('test'); $userID = $_SESSION['userID']; $sql="SELECT * FROM user WHERE userID='$userID'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $userID and $pswd, table row must be 1 row if($count == 1) { // checks dates if ($exp_date >= $todays_date) { // billing is up to date echo "Welcome: "; echo $_SESSION['userID']; } else { // billing has expired echo "<meta http-equiv='refresh' content='0;url=expBilling.php'>"; } } // END verify billing } // user is logged in and their billing is good else { echo "Welcome: "; echo "Non-user can view this stuff."; echo "<br><a href='form.php'>Click here to register</a>"; } // end session ?> These are all test pages once I get the coding right I will incorporate it into the real pages. Hello. I am coding a remember me feature. Everything is working, except i am being logged in using cookies even when i want to use a session. To login using a cookie i must select the checkbox, for sessions i must leave it blank. Here is my code, if someone could spot a mistake i would be really grateful. Login page Code: [Select] <?php ob_start(); // starting session... session_start(); // requiring connection... require("functions.php"); // assigning variables... $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $submit = mysql_real_escape_string($_POST['submit']); $rememberme = $_POST['rememberme']; // querying database... $query = mysql_query("SELECT * FROM users WHERE username = '$username'"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $db_username = $row['username']; $db_password = $row['password']; } } // verifying login details... if ($submit) { if (!empty($username) && !empty($password)) { if ($username == $db_username && $password == $db_password) { if ($rememberme = "on") { setcookie("username", $username, time() + 7200); header('Location: tablets.php'); } else { $_SESSION['username'] = $db_username; $url = $_SESSION['origin'] ? $_SESSION['origin'] : "main.php"; unset($_SESSION['origin']); header('Location: ' . $url); exit; } } else { echo "Incorrect login details"; } } else { echo "You must type in username and password"; } } ob_end_flush(); ?> Login form Code: [Select] <?php session_start(); require("connect.php"); if (isset($_SESSION['username']) || isset($_COOKIE['username'])) { header('Location: main.php'); } ?> <!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" xml:lang="en" lang="en"> <head> <title>Login</title> <link rel="stylesheet" type="text/css" href="form.css" /> </head> <body> <form method="post" action="login.php"> <div class="box"> <h1>Login</h1> <label> <span>Username</span> <input type="text" class="input_text" name="username" id="name" /> </label> <label> <span>Password</span> <input type="password" class="input_text" name="password" id="password" /> </label> <input type="checkbox" name="rememberme" /> <label> <input type="submit" class="button" value="Login" name="submit" /> </label> </div> </form> </body> </html> Hi What is the best way of handling a login system with sessions, I have read that you should never hold the password in a session, so what should you hold in the session in order to access a users data? I'm using a login form which allows me enter the pages as member only the only thing that I need to do is to include the file safe.php and the user has to login in order to see the content of this page. so far so good. if I use my subscription forms ( spread over 2 pages) the first page can be filled in properly however when I come to the second page (where I included the safe.php aswell I think I loose the session ID that I got after logging in the first time) I am redirected to the login page which I don't want. how can I avoid this? this is the content of safe.php Code: [Select] <?php // Pagina: safe.php: Includen if you want te securise your page just add it at the top of your page include("config.php"); if(isset($_SESSION['user_id'])) { // Inloggen correct, updaten laatst actief in db $sql = "UPDATE gebruikers SET lastactive=NOW() WHERE id='".$_SESSION['user_id']."'"; mysql_query($sql); }else{ if(isset($_COOKIE['user_id'])) { $sql = "SELECT wachtwoord,status FROM gebruikers WHERE id='".$_COOKIE['user_id']."'"; $query = mysql_query($sql); $rij = mysql_fetch_object($query); $dbpass = htmlspecialchars($rij->wachtwoord); $dbstatus = htmlspecialchars($rij->status); if($dbpass == $_COOKIE['user_password']) { $_SESSION['user_id'] = $_COOKIE['user_id']; $_SESSION['user_status'] = $dbstatus; }else{ setcookie("user_id", "", time() - 3600); setcookie("user_password", "", time() - 3600); echo "Cookies incorrect. Cookies verwijderd."; header("Location: inloggen.php"); } }else{ header("Location: inloggen.php"); } } ?> Hello guys, Is there on web any updated tutorial on how can I add Facebook login on my simple php login script? Any problems with the following? Is there a better way to do it? Thanks I get this errr message Notice: Undefined index: user in C:\wamp\www\Login\login.php on line 25 Here is line 25: $_SESSION['user'] == $form_username ; Here is the whole page. <?php session_start(); ?> <html> <head> <title>Login</title> <?php include('logic.inc'); ?> </head> <body> <?php if (!isset($_POST['user_name']) && isset($_POST['password'])) { die("Please enter both a username and password"); } $form_username = $_POST['user_name']; $form_password = $_POST['password']; mysqlConnect(); loginvar(); if($passdb = $form_password && $userdb = $form_username) { $_SESSION['user'] == $form_username ; echo "<hr />"; echo "Login Sucssesful <br /> "; echo '<a href="/login/index.php">Return Home</a>'; } else { die("User name does not match password"); } ?> </body> </html> Hellp! Hello, For some time I have been wondering which one is a better means to transfer an error from a processing file back to the main page, for example a user fills in a wrong username or password at index.php which is submitted for processing to login.php. What is the best means to transfer the error "Wrong username or password" from login.php back to index.php for display, so far i was using a $_SESSION variable but i wonder how effective it can be. I was then told $_GET variables are a good choice as well, i dont think submitting a form to itself is a good solution. Please advice me on the best means to proceed with this. Thanx in advance Hello again, I posted a question earlier about an include issue which I managed to fix but now I am dealing with a completely new error message and unlike before I don't even have a basic Idea of what is going on. The error in question is - Quote An error occurred in script 'C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\IUS\Login\form_process.php' on line 10: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\IUS\Index.php:1) Date/Time: 1-10-2012 16:49:31 the code for form_process.php is as follows Code: [Select] <?php # Script 16.8 - login.php // This is the login page for the site. require_once ('login/config2.inc.php'); // Start output buffering: ob_start(); // Initialize a session: session_start(); if (isset($_POST['submitted'])) { require_once (MYSQL); // Validate the email address: if (!empty($_POST['email'])) { $e = mysqli_real_escape_string ($dbc, $_POST['email']); } else { $e = FALSE; } // Validate the password: if (!empty($_POST['pass'])) { $p = mysqli_real_escape_string ($dbc, $_POST['pass']); } else { $p = FALSE; } if ($e && $p) { // If everything's OK. // Query the database: $q = "SELECT user_id, first_name, user_level FROM users WHERE (email='$e' AND pass=SHA1('$p')) AND active IS NULL"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); if (@mysqli_num_rows($r) == 1) { // A match was made. // Register the values & redirect: $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC); mysqli_free_result($r); mysqli_close($dbc); $url = BASE_URL . 'index.php'; // Define the URL: ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { // No match was made. echo '<p class="error">Either the email address and password entered do not match those on file or you have not yet activated your account.</p>'; } } else { // If everything wasn't OK. echo '<p class="error">Please try again.</p>'; } mysqli_close($dbc); } // End of SUBMIT conditional. ?> The process also uses config2.php so I am including the code for that in-case it helps Code: [Select] <?php # Script 16.3 - config.inc.php // ********************************** // // ************ SETTINGS ************ // // Flag variable for site status: define('LIVE', FALSE); // Admin contact address: define('EMAIL', 'email@gmail.com'); // Site URL (base for all redirections): define ('BASE_URL', 'localhost/IUS'); // Location of the MySQL connection script: define ('MYSQL', 'login/mysqli_connect.php'); // Adjust the time zone for PHP 5.1 and greater: date_default_timezone_set ('US/Eastern'); // ************ SETTINGS ************ // // ********************************** // // ****************************************** // // ************ ERROR MANAGEMENT ************ // // Create the error handler: function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) { // Build the error message. $message = "<p>An error occurred in script '$e_file' on line $e_line: $e_message\n<br />"; // Add the date and time: $message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />"; // Append $e_vars to the $message: $message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n</p>"; if (!LIVE) { // Development (print the error). echo '<div class="error">' . $message . '</div><br />'; } else { // Don't show the error: // Send an email to the admin: mail(EMAIL, 'Site Error!', $message, 'From: you@youremail.com'); // Only print an error message if the error isn't a notice: if ($e_number != E_NOTICE) { echo '<div class="error">A system error occurred. We apologize for the inconvenience.</div><br />'; } } // End of !LIVE IF. } // End of my_error_handler() definition. // Use my error handler. set_error_handler ('my_error_handler'); // ************ ERROR MANAGEMENT ************ // // ****************************************** // ?> At first I thought it was because cookies weren't enabled but I am positive they are, so I am really at a loss as-to what's going on, there is more to the error message, though its quite long and will take me a few minutes to go through and remove/alter any sensitive information. I keep getting an error code when running my php, it states: Parse error: syntax error, unexpected $end in W:\www\blog\login.php on line 33 Line 33 is </html> Code: [Select] <?php mysql_connect ("localhost", "root", ""); mysql_select_db("blog"); ?> <html> <head> <title>Login</title> </head> <body> <?php if(isset($_POST['submit'])){ $name = $_POST['name']; $pass = $_POST['password']; $result = mysql_query("SELECT * FROM users WHERE name='$name' AND pass='$pass'"); $num = mysql_num_rows($result); if($num == 0){ echo "Bad login, go <a href='login.php'>back</a>"; }else{ session_start(); $SESSION ['name'] = $name; header("Location: admin.php"); } ?> <form action='login.php' method='post'> Username: <input type='text' name='name' /><br /> Password: <input type='password' name='password' /><br /> <input type='submit' name='sumbit' value='Login!' /> </form> </body> </html>Can any one advise me whats wrong? Hey, could someone help me with login script ? I've got registration script. It contains 3 files: reg.php <?php require_once 'database.php'; ?> <h1><strong>Register</strong></h1> <form name="register" method="post" action="regcheck.php"> <label> <input type="text" name="user" id="user"> Username<br /> </label> <br /> <label> <input type="password" name="pass" id="pass"> Password<br /> </label> <br /> <label> <input type="text" name="email" id="email"> Email<br /> </label> <label> <input type="submit" name="reg" id="reg" value="Register"> </label> </form> regcheck.php <?php $email = $_POST['email']; if( isset( $_POST['user'] ) && isset( $_POST['pass'] ) && isset( $_POST['email'] ) ) { if( strlen( $_POST['user'] ) < 4 ) { echo "Username is too short"; } elseif( strlen( $_POST['pass'] ) < 4 ) { echo "Password is too short"; } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Bad email address"; } elseif( $_POST['pass'] == $_POST['user'] ) { echo"Username and password can't be the same"; } else { include( 'database.php' ); $username = mysql_real_escape_string( $_POST['user'] ); $password = mysql_real_escape_string( $_POST['pass'] ); $email = mysql_real_escape_string( $_POST['email'] ); $sqlCheckForDuplicateN = "SELECT username FROM user WHERE username = '". $username ."'"; $sqlCheckForDuplicateE = "SELECT email FROM user WHERE email = '". $email ."'"; if( mysql_num_rows( mysql_query( $sqlCheckForDuplicateE ) ) == 0 && mysql_num_rows( mysql_query( $sqlCheckForDuplicateN ) ) == 0 ) { $sqlRegUser = "INSERT INTO user( username, password, email ) VALUES( '". $username ."', '". $password ."', '". $email ."' )"; if( !mysql_query( $sqlRegUser ) ) { echo "You Could Not Register Because Of An Unexpected Error."; } else { echo "You Are Registered And Can Now Login"; } } elseif( !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateE ) ) == 0)) { echo "The Email You Have Entered Is Already Being Used. Please Try Another One."; } elseif( !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateN ) ) == 0)) { echo "The Username You Have Entered Is Already Being Used. Please Try Another One."; } elseif( !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateE ) ) == 0) && !(mysql_num_rows( mysql_query( $sqlCheckForDuplicateN ) ) == 0)) { echo "The Email and Username You Have Entered Is Already Being Used. Please Try Another One."; } } } else { echo "You Could Not Be Registered Because Of Missing Data."; } ?> database.php <? $con = mysql_connect('host','username','password'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('dbname'); ?> So could someone help me with login ??? Hi, I am trying to make a login script that uses the user's id from the database, and tries to match it up with the user and password sent by the login form. My checklogin.php page, just jumps back to the index.php page for some reason. I don't know why. I get the following errors, any help greatly appreciated. thank you. Notice: Undefined index: myusername in /hermes/bosweb/web173/b1739/public_htmlchecklogin.php on line 19 Notice: Undefined index: mypassword in /hermes/bosweb/web173/b1739/public_html/checklogin.php on line 20 Wrong Username or Password Here is my code to check the id. I can't figure out what is wrong. Code: [Select] <?php ini_set ("display_errors", "1"); error_reporting(E_ALL); $host = ""; $database = ""; $username = ""; $password = ""; $tbl_name = "users"; $conn = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error()); if($conn) { mysql_select_db($database); } else { echo "failed to select database"; } // 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 id FROM $tbl_name WHERE username='$myusername' and password= SHA1('$mypassword')"; $result=mysql_query($sql); $query_data = mysql_fetch_row($result); // Mysql_num_row is counting table row $count=mysql_num_rows($result) ; // If result matched id, table row must be 1 row if($count==1){ session_start(); $_SESSION['userid']=$query_data[0]; header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> I am looking to use this for an admin panel.
session_start.php
"session_start()" "if statement" where it checks if a successful login is givenIs it necessary to include "session_start.php" into the top of each script file? If I just include "session_start.php" into the top of the "main" file where the other script files are included inside of the "main" as well, then I have it in ways where the other script files could get called up through the URL.(?) I thought it is a bit too much to include "session_start.php" into each script file. Is there a way where this can be done with more simple ways? I would appreciate the suggestions a lot. Hello everyone, I am brand new to php and am starting off my journey by trying to create a simple login/register script. I have run into a bit of difficulty, however, and cannot seem to get this to work. I know that the register script is very basic (lacks strlen check, doesn't verify that both passwords are the same, etc.), but for the time being I simply want to have a functional script. Then I can continue learning by adding more components. Here are the login.php, checklogin.php, and register.php files (in this order). I believe that the login/checklogin files work, but the register file just shows the form without actually writing to DB when it is submitted. Thank you very much for your help. Code: [Select] <html> <body> <b> Member Login </b> <br /> <form name="input" action="checklogin.php" method="post"> Username : <input type="text" name="myusername" id="username"> <br /> Password : <input type="password" name="mypassword" id="password"> <br /> <input type="checkbox" name="remember" value="checkbox"> Remember me <br /> <input type="submit" value="Login"> Not a member? <a href="./register.php">Register!</a> </form> </body> </html> Code: [Select] <?php $host="localhost"; $usr="root"; $pwd=""; $db="MemberDB"; $tbl_name="members"; mysql_connect($host, $usr, $pwd) or die("Unable to connect"); mysql_select_db($db) or die("Unable to select database"); $myusr = $_POST['myusername']; $mypswd = md5($_POST['mypassword']); $myusername = stripslashes(strip_tags($myusr)); $mypassword = stripslashes(strip_tags($mypswd)); $myusername = mysql_real_escape_string($myusr); $mypassword = mysql_real_escape_string($mypswd); $sql="SELECT *FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if ($count==1) { session_register("myusername"); session_register("mypassword"); header("location:menu.php"); } else { echo "Incorrect Username or Password"; } ?> Code: [Select] <?php $host="localhost"; $usr="root"; $pwd=""; $db="MemberDB"; $tbl_name="members"; mysql_connect($host, $usr, $pwd) or die("Unable to connect"); mysql_select_db($db) or die("Unable to select database"); if (isset($_POST['register'])) { $query = "INSERT INTO members ('username', 'password', 'email') VALUES('$_POST[username]', 'md5($_POST[password1])', '$_POST[email]')"; mysql_query($db,$query) or die(); mysql_close(); echo "You have successfully registered!"; } else{ ?> <html> <body> <b> Register</b> <br /> <form name="register" action="./register.php" method="post"> Username : <input type="text" name="username" id="username"> <br /> Password : <input type="password" name="password" id="password1"> <br /> Confirm Password : <input type="password" name="password2" id="password2"> <br /> Email: <input type="text" name="email" id="email"> <br /> <input type="submit" value="register"> </form> </body> </html> <?php } ?> 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); ?> |