PHP - Php Session And Login Trouble
I'm trying to implement sessions into my website. At the moment index.php contains a login form that posts to AccountManagement.php. AccountManagement.php then checks the database to see if they have entered a correct username/password combination. This all works fine, however I would like the site to remember that a user has logged in, and not tell them that they have entered an invalid password every time they come to this page by any means other than index.php's login form (e.g. a back button on a page that follows from AccountManagement). I have tried for days to get this to work using a for loop that checks if the session is started, but I can't seem to get the placement/syntax correct.
Any help would be greatly appreciated. AccountManagement.php: Code: [Select] <?php include ("Includes/database.php"); include ("Includes/htmlheader.php"); dbconnect ("localhost", "xxxxx", "xxxxx", "xxxxx"); $query=sprintf("SELECT wowUsername, Password, UserID FROM Users WHERE (((wowUsername)=\"%s\") AND ((Password)=\"%s\"));", $_POST['Username'], $_POST['Password']); $result=mysql_query($query); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} if (mysql_num_rows($result) !=1) { $errormessage= "Incorrect Username or Password, please try again."; include ("Includes/error.php"); } else { $row=mysql_fetch_assoc($result); $CustomerID = $row['UserID']; $query2=sprintf("SELECT CustomerID, FName FROM Customers WHERE CustomerID=$CustomerID"); $result2=mysql_query($query2); $row2=mysql_fetch_assoc($result2); $_SESSION['UserID']=$CustomerID; ?> <form action="index.php" id="home" name="home" style="width: 8em"></form> <h1> Account Management </h1> <p><h3 align="center">Welcome <?php echo $row2['FName'];?>, use the buttons below to manage your subscriptions.<h3><br /> <h2> <form action="Subscription.php" id="subs" name="subs"> <p> <input class="button5" name="Setup" type="submit" value="New Subscription" align="center" /></p> </form></h2> <form action="AccountUpdate.php" id="remove" name="remove" style="width: 8em"> <p> <input class="button5" name="NewDetails" type="submit" value="Update Details" /> </p></form> </p> <p> <form action="AccountCancel.php" id="remove" name="remove" style="width: 8em"> <input name="Logout3" type="submit" class="button5" value="Cancel Account" align="right" /> </form> </p> <p> <br /> <form action="index.php" id="remove" name="remove" style="width: 8em"> <input class="button5" name="Logout" type="submit" value="Log Out" /> </p> </p> <?php } ?> </div> </body> </html> </form> htmlheader.php: Code: [Select] <?php error_reporting(E_ERROR | E_WARNING | E_PARSE ); if(!isset($_SESSION)) { session_start(); $_SESSION['UserID']=0; } ?> <!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><link rel="stylesheet" type="text/css" href="CSS/Styles.css"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Account Management</title> </head> <body> </form> <div id="content"> Similar Tutorialsin my login script i have the following which searches for the username they inputted and then adds their user id to the table sessions in the database. $result = mysql_query("SELECT * FROM ".DB_PREFIX."members WHERE user_username = '$username' AND user_password = '$password'"); if(mysql_num_rows($result) != 1) { $val_error = 'Username and Password incorrect.'; } else { $row = mysql_fetch_array($result); $browser = $_SERVER['HTTP_USER_AGENT']; $_SESSION['user_id'] = $row['user_id']; $_SESSION['session'] = session_id(); mysql_query("INSERT INTO ".DB_PREFIX."sessions VALUES(NULL, '".$_SESSION['user_id']."', '".$_SESSION['session']."', '".$_SERVER['REMOTE_ADDR']."', '".$_SERVER['HTTP_USER_AGENT']."', '".date('Y-m-d')."')"); if ($_SESSION['backpage']) { header('Location: '.$_SESSION['backpage']); } else { header('Location: index.php'); } } then on pages which i want only logged in members to access i have the following: if ($_SESSION['user_id'] == '') { header ('Location: '.SITE_ROOT.'/login.php'); } else { REST OF CODE } but when i login and try to access a page which requires you to be logged in i am directed back to index.php. I have nothing which does that. if you are not logged in you are redirected to login.php but it doesnt seem to work. Any ideas? Hello, I have the following code. I am trying to have it same the searches save for 30 days. I can't tell exactly how long this works for because it does work for a while but when I open the browser the following day, the information is lost. The server time is accurate. Does anyone have any clue to why this might not work? session_set_cookie_params(2592000); session_name('test_mysearches'); session_start(); $rqstsignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));if(!isset($_SESSION['mysearches'])) { $_SESSION['mysearches'] = array($_GET['s']);} else { if ($_GET['s'] != '') { $_SESSION['mysearches'] = array_filter($_SESSION['mysearches'], 'strlen'); if ($_SESSION['LastRequest'] != $rqstsignature) { // not a refresh array_unshift($_SESSION['mysearches'], $_GET['s']); $_SESSION['LastRequest'] = $rqstsignature; while(count($_SESSION['mysearches']) > 5) { array_pop($_SESSION['mysearches']); } } } } () thanks in advance. errors: Deprecated: Function session_register() is deprecated in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 18 Warning: session_register() [function.session-register]: Cannot send session cookie - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/login.php:18) in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 18 Warning: session_register() [function.session-register]: Cannot send session cache limiter - headers already sent (output started at /Applications/XAMPP/xamppfiles/htdocs/login.php:18) in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 18 Deprecated: Function session_register() is deprecated in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 22 Code: Code: [Select] <?php if ($_POST['email']) { include_once "connect_to_mysql.php"; $email = stripslashes($_POST['email']); $email = strip_tags($email); $email = mysql_real_escape_string($email); $password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); $password = md5($password); $sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$password' AND emailactivated='1'"); $login_check = mysql_num_rows($sql); if($login_check > 0){ while($row = mysql_fetch_array($sql)){ $id = $row["id"]; session_register('id'); $_SESSION['id'] = $id; $username = $row["username"]; session_register('username'); $_SESSION['username'] = $username; mysql_query("UPDATE members SET lastlogin=now() WHERE id='$id'"); header("location: member_profile.php?id=$id"); exit(); } } else { print '<br /><br /><font color="#FF0000">No match in our records, try again </font><br /> <br /><a href="login.php">Click here</a> to go back to the login page.'; exit(); } } ?> any help really appreciated...thanks!! Can someone please explain to me why I cant seem to get my mysql update line to work. I have been trying for a while an still nothing. I am new in php and need some help getting this to work. Please be gentle. a good explaination in newbie talk would be appreciated. The session variable I echoed out does work so I know I am reading the variable in from the other page. thanks <?php session_start(); /* Server side scripting with php CISS 225 Lab # Final Project */ //This section will create variables collected from information sent //by the post method on the createUserProcess. /* $_SESSION['city'] = $_POST['city']; $_SESSION['state'] = $_POST['state']; $_SESSION['zipCode'] = $_POST['zipCode']; $_SESSION['profession'] = $_POST['profession']; $_SESSION['activities'] = $_POST['activities']; $_SESSION['hobbies'] = $_POST['hobbies']; */ $city = $_POST['city']; $state = $_POST['state']; $zipCode = $_POST['zipCode']; $profession = $_POST['profession']; $activities = $_POST['activities']; $hobbies = $_POST['hobbies']; $db = mysql_connect("localhost", "root", ""); mysql_select_db("accountprofile",$db); echo $_SESSION['Email']; //$query = "UPDATE accountprofile SET city = '$city', state = '$state', zipcode = '$zipCode', profession = '$profession', " . " //activities = '$activities', hobbies = '$hobbies' WHERE lastName = 'Hildebrand'"; $query = "UPDATE accountprofile SET city = '$city', state = '$state', zipcode = '$zipCode', profession = '$profession', activities = '$activities', hobbies = '$hobbies' WHERE userName = " .$_SESSION['Email'].""; mysql_query($query,$db); if (mysql_error()) { echo "$query<br />"; echo mysql_error(); } echo "THANK YOU!<br />"; echo "Your profile has been completed!<br />"; ?> I'm not sure where the issue really lies after the form submits it DOES perform the error messages if there is one, however if the username and password are atleast filled in and the user clicks Log In it doesn't do anything after that. login.php <?php /** * @author Jeff Davidson * @copyright 2010 */ if (isset($_POST['submitted'])) { require_once ('inc/login_functions.php'); require_once ('inc/dbconfig.php'); list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']); if ($check) { // OK! // Set the session data:. session_start(); $_SESSION['id'] = $data['id']; $_SESSION['firstname'] = $data['firstname']; // Redirect: $url = absolute_url ('loggedin.php'); header("Location: $url"); exit(); }else { // Unsuccessful! $errors = $data; } mysqli_close($dbc); } // End of the main submit conditional. include ('inc/login_page.php') ?> login_functions.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // This page defines two functions used by the login/logout process. /* This function determines and returns an absolute URL. * It takes one argument: the page that concludes the URL. * The argument defaults to index.php. */ function absolute_url($page = 'index.php') { // Start defining the URL... // URL is http://plus the host name plus the current directory: $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Remove any trailing slashing: $url = rtrim($url, '/\\'); // Add the page $url .= '/' . $page; // Return the URL: return $url; } // End of absolute_url() function. /* This function validates the form data (the username and password). * If both are present, teh database is queried. * The function requires a database connection. * The function returns an array of information, including: * - a TRUE/FALSE variable indicating success * - an array of either errors or the database result */ function check_login($dbc, $username = '', $password = '') { $errors = array(); // Initialize error array. // Validate the username if (empty($username)) { $errors[] = 'You forgot to enter your username.'; } else { $u = mysqli_real_escape_string($dbc, trim($username)); } // Validate the password: if (empty($password)) { $errors[] = 'You forgot to enter your password.'; } else { $p = mysqli_real_escape_string($dbc, trim($password)); } if (empty($errors)) { // If everythings OK. // Retrieve the firstname and lastname for the username/password combination: $q = "SELECT id, firstname FROM users WHERE username='$u' AND password=SHA('$p')"; $r = @mysqli_query($dbc, $q); // Run teh query. // Check the result: if (mysqli_num_rows($r) == 1) { // Fetch the record: $row = mysqli_fetch_array($r, MYSQLI_ASSOC); // Return true and the record: return array(true, $row); }else { // Not a match! $errrors[] = 'The username and password entered do not match those on file.'; } } // End of empty ($errrors) IF. // Return false and the errors: return array(false, $errors); } //End of check_login() function. ?> login_page.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // This page prints any errors associated with logging in and creates the login, including the form. // Prints any error messages, if they exists: if (!empty($errors)) { echo '<h1>Error!</h1> <p class="error">The following error(s) occured:<br />'; foreach ($errors as $msg) { echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p>'; } // Display the form: ?> <!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" /> <meta name="description" content="Caracole" /> <title>Titanium</title> <link HREF="favicon.ico" type="image/x-icon" rel="icon" /> <link HREF="favicon.ico" type="image/x-icon" rel="shortcut icon" /> <link rel="stylesheet" type="text/css" href="css/tripoli.simple.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/base.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/layout.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/theme.css" media="screen, projection, print" /> <link rel="stylesheet" type="text/css" href="css/icons.css" media="screen, projection, print" /> <script type="text/javascript" SRC="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> //<![CDATA[ document.write('<link rel="stylesheet" type="text/css" href="css/js/js.css" media="screen, projection, print" />'); //]]> $(document).ready(function(){ $(".close").click(function(){ $(this).parents(".message").hide("puff"); }); }); </script> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/ie/ie.css" media="screen, projection, print" /> <![endif]--> <!--[if lt IE 7]> <script src="js/DD_belatedPNG_0.0.7a-min.js" type="text/javascript"></script> <script> DD_belatedPNG.fix(' #header, h1, h1 a, .close, .field,.paginate .current, .icon, .required-icon'); </script> <link rel="stylesheet" href="css/ie/ie6.css" type="text/css" media="screen, projection"/> <![endif]--> </head> <body> <!-- Content --> <div id="login" class="content"> <div class="roundedBorders login-box"> <!-- Title --> <div id="title" class="b2"> <h2>Log In</h2> <!-- TitleActions --> <div id="titleActions"> <div class="actionBlock"> <a href="#">Forgot your password ?</a> </div> </div> <!-- /TitleActions --> </div> <!-- Title --> <!-- Inner Content --> <div id="innerContent"> <form action="login.php" method="post"> <div class="field"> <label for="username">Username</label> <input type="text" class="text" id="username" name="username" /> </div> <div class="field"> <label for="password">Password</label> <input type="password" class="text" id="password" name="password"/> </div> <div class="clearfix login-submit"> <span class="fleft"> <input type="checkbox" name="remember-me" id="remember-me" /> <label for="remember-me">Remember me</label> </span> <span class="fright"> <button class="button" type="submit" name="submit"><strong>Log In</strong></button> </span> </div> <input type="hidden" value="TRUE" name="submitted" /> </form> </div> <!-- /Inner Content --> <div class="bBottom"><div></div></div> </div> </div> </body> </html> loggedin.php <?php /** * @author Jeff Davidson * @copyright 2010 */ // The user is redirected here from login.php. session_start(); // Star the session. // If no session value is present, redirect the user: if (!isset($_SESSION['id'])) { require_once('inc/login_functions.php'); $url = absolute_url(); header("Location: $url"); exit(); } $page_title = 'Logged In!'; // Print a customized message: echo "<h1>Logged In!</h1> <p>You are now logged in, {$_SESSION['firstname']}!</p> <p><a href=\"logout.php\">Logout</a></p>"; ?> I thought I'd come back in and insert the file manager I have setup here. root/loggedin.php root/login.php root/inc/login_page.php root/inc/login_functions.php I am trying to create a login menu, but I keep getting the same errors. Ok here is what I'm trying to do. There is a link in a email that is sent out to the people who use this app. When they click on the email link they are brought to this site which is password protected. So they have to enter their username and password. What I want to below script to do is to log them in while checking to see if the $id variable is set. If it is, then the script is to take them to the page in the email link. If not take them to the submit job page. <?php $id=$_POST["id"]; $cmd = $_POST['cmd']; $connection = mysql_connect("host", "user", "pass"); mysql_select_db("database", $connection) or die(mysql_error()); switch($cmd) { case "login": $u = $_POST['username']; $p = $_POST['password']; $query = "SELECT * FROM login WHERE username='$u' AND password='$p'"; $result = mysql_query($query); $row = mysql_fetch_array($result); if (isset($id))($row){ session_start(); $_SESSION['user_id'] = $row[0]; $_SESSION['residentname'] = $row[1]; $_SESSION['unit_num'] = $row[2]; setcookie("TestCookie", time()+3600); /* expire in 1 hour */ $resite = "submitjob.php?do=viewone&id=$id"; header("Location:$resite"); exit(); } else if ($row){ session_start(); $_SESSION['user_id'] = $row[0]; $_SESSION['residentname'] = $row[1]; $_SESSION['unit_num'] = $row[2]; setcookie("TestCookie", time()+3600); /* expire in 1 hour */ $resite = "submitjob.php"; header("Location:$resite"); exit(); } else { echo "Sorry the app didn't find a match."; } break; } ?> This should be really simple, but I just can't figure out why it isn't working. It's my first time using sessions, so I'm probably doing something silly. It's just a login to an admin page. It's for a photo gallery, that's why the database is called "photo". This is the login page: Code: [Select] <?php session_start(); if(isset($_POST['user']) && isset($_POST['password'])){ $user = $_POST['user']; $password = sha1($_POST['password']); $photo = new mysqli('localhost', 'user', 'password', 'photo'); $login = $photo->query("select user, sha1(password) from settings where user = '$user' and sha1(password) = '$password'"); if($login->num_rows > 0){ $_SESSION['login'] = 1; ?> <META HTTP-EQUIV="Refresh" Content="0; URL=admin.php"> <?php } else { $badlogin = 1; } } ?> <html> <head> <style> body {margin-top: 50px;} td {text-align: right;} input {width: 200px;} </style> </head> <body><center> <?php if(isset($badlogin)){ ?> <span style="color: red;">Oops! Wrong login.</span><br><br> <?php } ?> <table> <form action="admin.php" method="post"> <tr><td>User:</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" value="Login" /></td></tr> </form> </table> </center></body> </html> And this is the admin page: Code: [Select] <?php session_start(); if($_SESSION['login'] != 1){ ?> <META HTTP-EQUIV="Refresh" Content="0; URL=login.php"> <?php } else { ?> <html> <head> </head> <body> Admin stuff here. </body> </html> <?php } ?> OK when i go to my website and login i stay login in intill i sign out but when im stilled loged in and click new tab and type my website i see the login table but im already loged in so i have to click on my logo to time to make the login table go away why if you need the login code i would be happy to give it to use Im trying to make sessions work with my script, its finding the user/pass in the database and redirects me to the homepage after but the parts that are supposed to show when the session is set are not showing. My code: <?php // Login Logic $username = ""; $err = ""; $err_style = ""; $err_style2= ""; //Checks if there is a login cookie if(isset($_SESSION['username'])) { //if there is, it logs you in and directes you to the members page $_SESSION['username'] = $username; $_SESSION['password'] = $password; //$username = $_COOKIE['user_id']; //$pass = $_COOKIE['pass_id']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());$quer++; while($info = mysql_fetch_array( $check )) { if ($pass != $info['password']) { } else { header("Location: index.php"); } } } //if the login form is submitted if (isset($_POST['submit'])) { // if form has been submitted // SANITISE $username = sanitize($_POST['username']); $pass = sanitize($_POST['password']); $red = sanitize($_POST['red']); // makes sure they filled it in if(!$_POST['username']) { $err = 'You did not fill in a required section'; $err_style = "style='border: 1px solid #CC0000'"; $show_login = 1; } if(!$_POST['password']) { $err = 'You did not fill in a required section'; $err_style2 = "style='border: 1px solid #CC0000'"; $show_login = 1; } // checks it against the database if (!$err) { $check = mysql_query("SELECT * FROM users WHERE username = '".$username."'")or die(mysql_error());$quer++; //Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { $err = 'User not found - please try again!'; $err_style = "style='border: 1px solid #CC0000'"; $show_login = 1; } while($info = mysql_fetch_array( $check )) { $info['password'] = stripslashes($info['password']); $pass = $pass; //gives error if the password is wrong if ($pass != $info['password']) { $err = 'Incorrect password, please try again.'; $err_style2= "style='border: 1px solid #B02B2C;'"; $show_login = 1; } else { session_start(); $_SESSION['username'] = $username; $_SESSION['password'] = $password; // if login is ok then we add a cookie //$hour = time() + 3600; //setcookie("user_id", $username, $hour); //setcookie("pass_id", $pass, $hour); //then redirect them to the members area if (!$red) { header("Location: index.php"); } else { header("Location: $red.php"); } exit; } } } } ?> And: <?php session_start(); //checks cookies to make sure they are logged in if(isset($_SESSION['username'])) { $_SESSION['username'] = $username; $_SESSION['password'] = $password; //$username = $_COOKIE['user_id']; //$pass = $_COOKIE['pass_id']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); $quer++; while($info = mysql_fetch_array( $check )) { //if the cookie has the wrong password, they are taken to the login page if ($pass != $info['password']) { header("Location: login.php"); } //otherwise they are shown the admin area else { // Update some info session_start(); $_SESSION['username'] = $username; $_SESSION['password'] = $password; //setcookie ("user_id", $_COOKIE['user_id'], time() + 3600 ); //setcookie ("pass_id", $_COOKIE['pass_id'], time() + 3600 ); // Get some basic user details, so we can use these later! $uname = $info['username']; $uID = $info['user_id']; $email = $info['email']; $loggedin = 1; $admin_user = $info['admin']; } } } ?> Hi guys, I have a loggin page which works fine except it doesnt pass the session, could someone help me to see what mistake im making? once users login they will be diverted to another page where is their profile page, i have echoed the session in member page but it doesnt read it. i have attached both codes (member page and login page) below, thanks in advance for your help code is below: login page code: Code: [Select] <?php //connect to database include '../include/db.php'; //we start a session here to help us pass the user login variable to other pages of the webs application while user is logged in. session_start(); //php login // if post has been successfully sent, do the action below if ($_POST['login']){ // get data from form fields $email=strip_tags($_POST['email']); $password=strip_tags($_POST['password']); // check if email (username) and password have been inserted, if not show an error if($email == "" || $password == "") echo "Please enter your email address and postcode"; else { //check if email exists $checkemail=mysql_query("SELECT * FROM member WHERE EmailAddress='$email'"); //if exists we get the information from database if ($getrows=mysql_num_rows($checkemail)>=1){ while ($row=mysql_fetch_array($checkemail)) { $myemail=$row['EmailAddress']; $mypassword=$row['Password']; } //convert the password to md5 $pass=md5($password); //now we check if entered email and password match our database record if ($myemail==$email && $mypassword==$pass) { $_SESSION['emailaddress']=$myemail; //update the loggedin to 1 so we users go to next page, our website will compare if users is logged in or not $update=mysql_query("UPDATE member SET loggedin='1' WHERE EmailAddress='$email'"); //if details exist we get the users first name our database to pass this information along with our sessions $getuser=mysql_query ("SELECT * FROM member WHERE EmailAddress='$email'"); while($row=mysql_fetch_array($getuser)) { $firstname=$row['FirstName']; } echo "Welcome $firstname, <a href='profile.php'>Click here</a> to be directed to your profile"; } } else { echo "This user doesn't exists"; } } } ?> and this is the member page so far Code: [Select] <?php //connect to database include '../include/db.php'; //we start a session here to help us pass the user login variable to other pages of the webs application while user is logged in. session_start(); echo "Welcome ".$_SESSION['emailaddress'].""; ?> This is my first attemp at a log in system for a website. Everything seems to work fine until the "successful" IF function near the end. All I get it an output of "?>" instead of a redirect to the file "login_success.php". Any help would be GREATLY appreciated!! Tom <?php // Connect to server and select databse. mysql_connect("localhost", "scripts3_public", "sfj123!")or die("cannot connect"); mysql_select_db("scripts3_sfj")or die("cannot select DB"); // username and password sent from form $fusername=$_POST['fusername']; $fpassword=$_POST['fpassword']; // To protect MySQL injection (more detail about MySQL injection) $fusername = stripslashes($fusername); $fpassword = stripslashes($fpassword); $fusername = mysql_real_escape_string($fusername); $fpassword = mysql_real_escape_string($fpassword); $sql="SELECT * FROM `users` WHERE `User name` = '$fusername' AND `Password` = '$fpassword'"; $result=mysql_query($sql); if(!mysql_num_rows($result)) {echo "No results returned.";} // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $fusername and $fpassword, table row must be 1 row if($count==1){ // Register $fusername, $fpassword and redirect to file "login_success.php" session_register("fusername"); session_register("fpassword"); header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> I don't know how to solve this error;
Parse error: syntax error, unexpected '$db' (T_VARIABLE)
code:
<!DOCTYPE html> <html> <head> <style type="text/css" media="screen"> .ss { border-width: 1px; border-style:solid; width: 100px; height: 100px; </style> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> </head> <body> <form action="index.php" method="post"> <table align="center" class="ss"> <tr> <td>Name<input type="text" name="name"> </td> </tr> <tr> <td>Pass :<input type="password" name="pass"> </td> </tr> <tr> <td>Email<input type="text" name="eml"> </td> <tr> <td><input type="submit" name="sb"> </td> </table> </form> </body> </html> <?php include "db.php"; session_start(); if(isset($_POST['sb'])) { $name=mysqli_real_escape_string($con, $_POST['eml']); $pass=mysqli_real_escape_string($con, $_POST['pass']); $usr=mysqli_real_escape_string($con,'user'); $std='std'; $type='admin'; $qer="select * from users where eml='$name' AND pass='$pass' AND type='$type'"; $sql=mysqli_query($con,$qer); $qer=" select * from users where eml='$name' AND pass='$pass' AND type='$std'"; $sql1=mysqli_query($con,$qer); $qer=" select * from users where eml='$name' AND pass='$pass' AND type='$usr'"; $sql3=mysqli_query($con,$qer); $fe=mysqli_fetch_array($sql); if(is_array($fe)) { $name=$name; $pass=$pass; { header("location:wel.php?msg=Scuessfull login"); } echo "Admin of this site"; } else if($fe=mysqli_fetch_array($sql1)){ if(is_array($fe)) $name=$name; $pass=$pass; echo "Moderator of the site"; { header("location:mod.php?msg=Scuessfull login"); } } else if($fe=mysqli_fetch_array($sql3)){ if(is_array($fe)) $name=$name; $pass=$pass; $_SESSION['eml'] =true; header("location:sim.php?msg=Scuessfull login"); echo "Simple user this site"; } else { echo "invalid pass"; } } ?>
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'm trying to create a simple session on a form page that determines if you've signed in. If you haven't, it kicks you to the login page. But for some reason, what I have isn't doing that. When I open the page, it loads, but only prints the url on a blank page, instead of actually going to the url. Code: [Select] <html> <title>form</title> <link rel="stylesheet" type="text/css" href="style.css"> <body> <?php session_start(); if(isset($_SESSION['id']) && is_numeric($_SESSION['id'])) { if (isset($_POST['submitted'])) { $errors = array(); if (empty($_POST['scientific_name'])) { $errors[] = 'you forgot to enter the scientific name'; } else { $sn = trim($_POST['scientific_name']); } if (empty($_POST['common_name_english'])) { $errors[] = 'you forgot to enter the common name'; } else { $cne = trim($_POST['common_name_english']); } $description4 = trim($_POST['common_names_spanish']); $description5 = trim($_POST['common_names_french']); $description6 = etc. etc. if (empty($errors)) { require_once ('3_z_mysq1_c0nn3ct.php'); $query = "INSERT INTO plantae (scientific_name, common_name_english, etc.) VALUES ('$sn', '$cne', '$description4', '$description5', '$description6', '$description7', etc.)"; $result = @mysql_query ($query); if ($result) { if(isset($_POST['scientific_name'])) { $plant_id=mysql_insert_id(); } exit(); } else { echo 'system error. No plant added'; echo '<p>' . mysql_error() . '<br><br>query:' . $query . '</p>'; exit(); } mysql_close(); } else { echo 'error. the following error occured <br>'; foreach ($errors as $msg) { echo " - $msg<br>\n"; } } // end of if } // end of main submit conditional echo '<form action="insertaplant1.php" method="post"><fieldset><legend><b>Enter your new plant here</b></legend> form fields here. </form>'; } else { $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); if((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr($url, 0, -1); } $url .= '/login.php'; echo $url; exit(); } ?> Hello, for some reason I am unable to get the following code to work: Code: [Select] <?php echo "<h1>Login</h1>"; if ($_SESSION['uid']) { echo " You are already logged in, if you wish to log out, please <a href=\"./logout.php\">click here</a>!\n"; } else { if (!$_POST['submit']) { echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n"; echo "<form method=\"post\" action=\"./login.php\">\n"; echo "<tr><td>Username</td><td><input type=\"text\" name=\"username\"></td></tr>\n"; echo "<tr><td>Password</td><td><input type=\"password\" name=\"password\"></td></tr>\n"; echo "<tr><td colspan=\"2\" align=\"right\"><input type=\"submit\" name=\"submit\" value=\"Login\"></td></tr>\n"; echo "</form></table>\n"; }else { $user = addslashes(strip_tags(($_POST['username']))); $pass = addslashes(strip_tags($_POST['password'])); if($user && $pass){ $sql = "SELECT id FROM `users` WHERE `username`='".$user."'"; $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) > 0){ $sql2 = "SELECT id FROM `users` WHERE `username`='".$user."' AND `password`='".md5($pass)."'"; $res2 = mysql_query($sql2) or die(mysql_error()); if(mysql_num_rows($res2) > 0){ $query = mysql_query("SELECT locked FROM `users` WHERE `username`='".$user."'"); $row2 = mysql_fetch_assoc($query); $locked = $row2['locked']; $query = mysql_query("SELECT active FROM `users` WHERE `username`='".$user."'"); $row3 = mysql_fetch_assoc($query); $active = $row3['active']; $query = mysql_query("SELECT email FROM `users` WHERE `username`='".$user."'"); $row3 = mysql_fetch_assoc($query); $email = $row3['email']; if ($active ==1){ if ($locked == 0){ $date = date("j")."<sup>".date("S")."</sup> ".date("F, Y"); mysql_query("UPDATE users SET last_login='$date' WHERE username='$user'"); $row = mysql_fetch_assoc($res2); $_SESSION['uid'] = $row['id']; $previous = $_COOKIE['prev_url']; echo " You have successfully logged in as " . $user . "<br><br><a href='" . $previous . "'>Click here</a> to go to the previous page.\n"; }else { echo "Your acount has been locked out due to a violation of the rules, if you think there has been a mistake please <a href='contact.php'>contact us</a>."; } } else { echo "You need to activate your account! Please check your email ($email)"; } }else { echo " Username and password combination are incorrect!\n"; } }else { echo " The username you supplied does not exist!\n"; } }else { echo " You must supply both the username and password field!\n"; } } } ?> It says that I have logged in successfully but the session is not created. You can find the script here and log in with the username "test" and the password "testing". I'm not sure what more information I should add. Thanks, Cameron Hi: How do I set a password-protected page to time out after 20 minutes or so? I thought it was doing it on the below page, but it is not working. A tutorial I found online. Login.php Code: [Select] <form name="form1" method="post" action="myLogin.php"> <input name="myUserName" type="text" size="40" id="myUserName"> <br /><br /> <input name="myPassword" type="password" size="40" id="myPassword"> </div> <input type="submit" name="Submit" value="Login"> </form> myLogin.php Code: [Select] <?php ob_start(); // Connect to server and select database. //mysql_connect("$host", "$username", "$password")or die("cannot connect"); //mysql_select_db("$db_name")or die("cannot select DB"); // Define $myUserName and $myPassword $myUserName=$_POST['myUserName']; $myPassword=$_POST['myPassword']; // To protect MySQL injection (more detail about MySQL injection) $myUserName = stripslashes($myUserName); $myPassword = stripslashes($myPassword); $myUserName = mysql_real_escape_string($myUserName); $myPassword = mysql_real_escape_string($myPassword); $sql="SELECT * FROM myAdmins WHERE myUserName='$myUserName' and myPassword='$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 "a_Home.php" session_register("myUserName"); session_register("myPassword"); header("location:a_Home.php"); } else { echo " <html> ... </html> "; } ob_end_flush(); ?> myCheckLogin.php (added to each page to see if the person logged-in via Login.php): Code: [Select] <? session_start(); if(!session_is_registered(myUserName)){ header("location:Login.php"); } ?> Any help would be great. Thanks. Registration.php Code: [Select] <html> <head> <script type="text/javascript"> function a() { var x = document.login.username.value; var y = document.login.pass.value; if(x==""&& y=="") { alert("Please insert all message!"); return false; } if(x=="") { alert("Please insert an username!"); return false; } if(y=="") { alert("Please insert an password!"); return false; } } </script> </head> <?php session_start(); mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); //session_start(); $username = $_POST['username']; $password = $_POST['pass']; if (isset($_POST["submit"])) { $log = "SELECT * FROM regis WHERE username = '$username'"; $login = mysql_query($log); $number = mysql_num_rows($login); if ($number == 0) { print "That user does not exist in our database. <a href=registration.php><input type='button' value='Register'></a>"; } if ($number > 0) { $_SESSION['is_logged_in'] = 1; } if(!isset($_SESSION['is_logged_in'])) { } else { echo "<meta http-equiv='refresh' content='0; url=form2.php'>"; } } else { ?> <body> <table border="0"> <form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return a()"> <tr><td colspan=2><h1>Login</h1></td></tr> <tr><td>Username:</td> <td><input type="text" name="username" maxlength="40"></td></tr> <tr><td>Password:</td> <td><input type="password" name="pass" maxlength="50"></td></tr> <tr><td><input type="submit" name="submit" value="Register"></a></td> <td><input type="submit" name="submit" value="Login"></td></tr> </form> </body> <?php } ?> </html> form2.php Code: [Select] <?php session_start(); if (!isset($_SESSION['is_logged_in'])) { header("Location:login.php"); die(); // just to make sure no scripts execute } ?> <?php mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); $message=$_POST['message']; $n=$_POST['username']; if(isset($_POST['submit'])) //if submit button push has been detected { if(strlen($message)>1) { $message=strip_tags($message); $IP=$_SERVER["REMOTE_ADDR"]; //grabs poster's IP $checkforbanned="SELECT IP from ipbans where IP='$IP'"; $checkforbanned2=mysql_query($checkforbanned) or die("Could not check for banned IPS"); if(mysql_num_rows($checkforbanned2)>0) //IP is in the banned list { print "You IP is banned from posting."; } else { $thedate = date("U"); //grab date and time of the post $insertmessage="INSERT into chatmessages (name,IP,postime,message) values('$n','$IP','$thedate','$message')"; mysql_query($insertmessage) or die("Could not insert message"); } } } ?> <html> <head> <script type="text/javascript"> function addsmiley(code) { var pretext = document.smile.message.value; this.code = code; document.smile.message.value = pretext + code; } function a() { var x = document.smile.message.value; if(x=="") { alert("Please insert an message!"); return false; } } </script> <style type="text/css"> body{ background-color: #d8da3d } </style> </head> <body> <form name="smile" method="post" action="form2.php" onSubmit="return a()" > Your message:<br><textarea name='message' cols='40' rows='2'></textarea><br> <img src="smile.gif" alt=":)" onClick="addsmiley(':)')" style="cursor:pointer;border:0" /> <img src="blush.gif" alt=":)" onClick="addsmiley('*blush*')" style="cursor:pointer;border:0" /> <input type="hidden" name="username" value="<?php echo $n;?>"> <input type='submit' name='submit' value='Send' class='biasa' ></form> <br> <br> </body> </html> My problem is after i login it redirect to login page although im had put after login page its need to go to form2.php page may i know which problem because now only im learning session hey guys, Im trying to register a session from a login im making and for some reason its not working. here is my code: <?php session_start(); if(isset($_POST['username'])){ $username = $_POST['username']; //name of the text field for usernames $password = $_POST['password']; //likewise here just for the password //connect to the db $user = 'root'; $pswd = ''; $db = 'chat'; $conn = mysql_connect('localhost', $user, $pswd); mysql_select_db($db, $conn); //run the query to search for the username and password the match $query = "SELECT * FROM users WHERE username = '$username' AND password ='$password'"; $result = mysql_query($query) or die("Unable to verify user because : " . mysql_error()); //this is where the actual verification happens if(mysql_num_rows($result) == 1){ //the username and password match //so e set the session to true $_SESSION['username'] = $username; $_SESSION['uID'] = $result['user_id']; //$_SESSION['email'] = $result['email']; //and then move them to the index page or the page to which they need to go header('Location: index.php'); }else{ $err = 'Incorrect username / password.' ; } //then just above your login form or where ever you want the error to be displayed you just put in echo $err; } else ?> Im trying to make it so it also gets the user_id of the user logging in and creates a session for it. It works for the username part, and Im able to echo the username im logged in with, but for some reason it does want to work for the user_id part. This is what doesnt register $_SESSION['uID'] = $result['user_id']; Thanks for the upcoming help. |