PHP - Page Not Recognizing Login Session - Need To Manually Refresh - Please View Code
I have a strange problem. When a guest visits my contact-user.php page, they get a message telling them the must login before viewing the page.
After the guest logs in, they view the same page and it tells them they have to login again (keeps on looping). But if they manually refresh that page with the "you must be logged in" message, it recognizes the login and lets them in. How can I get this page to immediately recognize that the user is logged in and not require them to refresh the page manually? Here is my code for contact-user.php <?php session_start(); header("Cache-Control: private, max-age=10800, pre-check=10800"); header("Pragma: private"); header("Expires: " . date(DATE_RFC822,strtotime("+2 day"))); include("connection.php"); mysql_select_db("database"); if (isset($_SESSION['username'])) { ******** MY HTML PAGE CONTENT ******** } else { echo "<meta http-equiv='REFRESH' content='2;url=http://www.mysite.com/login.php'> <center><font color='#EE0000'><p>You must be logged in before negotiating. You will now be redirect to the login page.</p></font></center>"; } ?> Here is my code for login.php script: <?php include("connection.php"); mysql_select_db("database"); session_start(); if(isset($_POST['login'])){ $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $tUnixTime = time(); $sGMTMySqlString = gmdate("Y-m-d H:i:s", $tUnixTime); if (!$username || !$password) { print "Please fill out all fields."; exit; } $logres = mysql_num_rows(mysql_query("SELECT * FROM members WHERE username = '$username' and password = '$password'")); if ($logres <= 0) { print "Login failed. If you have not already, please signup. Otherwise, check your spelling and login again."; exit; } else { $_SESSION['username'] = $username; if (isset($_SESSION)) { echo'You are now logging in'; mysql_query("UPDATE members SET activity = '$sGMTMySqlString' WHERE username = '$username'"); } else { echo "You are not logged in!"; } echo'<html><head><meta http-equiv="REFRESH" content="1;url=http://www.mysite.com/members/' . $_SESSION['username'] . '/"></head><body></body></html>'; exit; } } ?> Similar TutorialsLogin.php Code: [Select] <?php session_start(); mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); $username = $_POST['username']; $password = $_POST['pass']; if (isset($_POST["submit"])) { $log = "SELECT * FROM regis WHERE username = '$username'"; $login = mysql_query($log); $row = mysql_fetch_array($login); $number = mysql_num_rows($login); if ($number > 0) { $_SESSION['username'] = $row['username']; $_SESSION['userlevel'] = $row['userlevel']; if($_SESSION['userlevel']==1) { $_SESSION['is_logged_in'] == 1; header("Location: form2.php"); } else if($_SESSION['userlevel']== 0) { $_SESSION['is_logged_in'] == 1; header("Location: registration.php"); } } Registration.php Code: [Select] <?php echo 'Welcome:' .$_SESSION['is_logged_in'];?> form2.php Code: [Select] <?php session_start(); if (empty($_SESSION['is_logged_in'])) { header("Location:chatframe.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']; $a=$_SESSION['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('$a','$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='submit' name='submit' value='Send' class='biasa' ></form> <br> <br> </body> </html> In this registration.php when im called back its appear nothing im means the number is not showing and the login code even im had also put the "$_SESSION['is_logged_in'] == 1;" outside if else userlevel statement and then i put $d= $_SESSION['is_logged_in'] == 1; and im echoing back but it is nothing im thinks something wrong in session is login and also still it cannot redirect to admin -form2.php when session is login in is 1 Is it possible to manually edit a SESSION (not cookie) from client side? Sort of how a user can easily edit a cookie's value. 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 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 ONE of my SESSION values isn't remaining after login while others do. This works fine on my localhost, it's on the live site that there is a problem and it just started yesterday. Before that it worked great. Out of the four SESSIONs made I can only echo three values on other pages, member id the most important doesn't transfered to other pages Notes: all these files are in the same folder, there is a SESSION started for the member id on the login page, you can see that it is used in the redirect below and the redirect works fine with the redirect going to the correct page " $home/member/index.php?user=$id_mem " Here is the login page // Here's the basic login page info <?php # login.php session_start(); ob_start() ...connect to db & header called... ...Form validation..... if ($e && $p) { // If everything's OK. // Query the database: $q = "SELECT id_mem, display_name, mem_group FROM sn_members WHERE (email='$e' AND password=SHA1('$p')) AND active IS NULL"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); // or die("Error: ".mysqli_error($dbc)); if (@mysqli_num_rows($r) == 1) { // If a match was made. // Register the values & redirect: // Give SELECTED elements a session $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC); $_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']); mysqli_free_result($r); // Update db for last login $id_mem = $_SESSION['id_mem']; // <<< SESSION member id has a value here because it's used in the redirect below $ip = $_SERVER['REMOTE_ADDR']; // Get ip address of person logging in $q = "UPDATE sn_members SET last_login = Now(), ip = '$ip' WHERE id_mem = '$id_mem' LIMIT 1"; $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); header("Location: $home/member/index.php?user=$id_mem"); exit(); // Quit the script. } ?> Here is the main page that a user would be redirect to above <?php // /member/ all member info is through this folder session_start(); ob_start(); if (isset($_GET['user']) && is_numeric($_GET['user'])) { $user = $_GET['user']; $user = $user; if ($user < 0) { header("Location: $home/index.php"); exit(); } } if ((!isset($_SESSION['id_mem'])) && (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])))){ // If not a logged in member redirect header("Location: $home/index.php"); exit(); // Quit the script. } ?> Thanks in advance for the help SJ Hello all, i have a feeling im doing something wrong, but i have no idea what. being server-side code, php should not show when you 'view page source' in your browser (or rather it should display as html), correct ? why, then am i seeing php code when i view page source? see attached image Hey everyone, So here is my problem. I have some code to display the amount of views that page has got. In this case it is the thread in my forums section. I have used the same code to show how many people have views a certain persons profile page and that works fine but when I use it on my forum thread page I get this error. Quote You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id='20' LIMIT 1' at line 1 Here is the section of code: Code: [Select] <?php $thread_id = preg_replace('#[^0-9]#i', '', $_GET['id']); $getThreadViews = mysql_query("SELECT view_count FROM forum_posts WHERE id='$thread_id' LIMIT 1") or die (mysql_error()); $row = mysql_fetch_assoc($getThreadViews); $counter = $row['view_count']; if($counter == 0){ $counter = 1; $startCounter = mysql_query("INSERT INTO forum_posts (view_count) VALUES ('$counter') WHERE id='$thread_id' LIMIT 1") or die (mysql_error()); } $threadViews = $counter+1; $appendCounter = mysql_query("UPDATE forum_posts SET view_count='$view_count' WHERE id='$thread_id'") or die (mysql_error()); ?> I have checked that there are no spelling errors so just wanted to show it to a fresh pair of eyes because its really starting to annoy me. Thanks in advance for any help. well basically im trying to do that the 'subject says. ive done my homework and had around 10 examples of using curl, but none of them worked in my case. this is the final code i'm using <?php $cookiefile = '/temp/cookies.txt'; #2 ways ive tried doing #$data = array('edit[username]' => 'REMOVED', 'edit[password]' => 'REMOVED', 'edit[submit]' => 'Login'); $data = array('username] => 'REMOVED', 'password' => 'REMOVED', 'submit' => 'Login'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://pokerrpg.com'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_exec($ch); curl_setopt($ch, CURLOPT_URL, 'http://pokerrpg.com/furniture_store.php'); $contents = curl_exec($ch); $headers = curl_getinfo($ch); echo $contents; curl_close($ch); unlink($cookiefile); ?> im not sure about the cookie file, but i just made a txt file to that location. and empty txt file. hope it's fine. the page i'm trying is http://pokerrpg.com, you can even look the source code that both of these fields do exist. when i run it, the output is a login page without logging in, so it does not log in. This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=353397.0 Hello everyone, When I submit my login form to go to my login page it goes to a white page and does not display an error. Code: [Select] <?php include("../secure/database.php"); if(!empty($_POST['loginsubmit'])){ if(!empty($_POST['email'])){ $email = securevar($_POST['email']); if(!empty($_POST['passconf'])){ $pass = securevar($_POST['passconf']); $q = "SELECT * FROM `accountinfo_db` WHERE `email` = '$email' AND `password` = '$pass'"; $res = mysql_query($q) or die(mysql_error()); $login = mysql_fetch_array($res); $id = $login['id']; $active = $login['active']; if($id>=1){ if($active==1){ $_SESSION['logged'] = $login['id']; $q = "UPDATE `accountinfo_db` SET `loggedtimes` = `loggedtimes`+'1' WHERE `id` = '$id'"; $res = mysql_query($q) or die(mysql_error()); $user = $login['username']; header("Location: ../mainframe.php?strmsg=Welcome Back $user"); }else{ header("Location: activate.php"); } }else{ header("Location: ../index.php?strmsg=Login Information Incorrect!"); } }else{ header("Location: ../index.php?strmsg=You did not enter a valid password!"); } }else{ header("Location: ../index.php?strmsg=You did not enter a valid email!"); } }else{ header("Location: ../index.php?strmsg=We are sorry but you are not allowed viewance of that directory!"); } ?> any help would be great. Brian Advance thank you. Can you help please. The error..... Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\wamp\www\test_dabase.php on line 24 code. Code: [Select] <?php //database connection. $DB = mysql_connect("localhost","root") or die(mysql_error()); if($DB){ //database name. $DB_NAME="mysql"; //select database and name. $CON=mysql_select_db($DB_NAME,$DB)or die(mysql_error()."\nPlease change database name"); // if connection. }if($CON){ //show tables. $mysql_show="SHOW TABLES"; //select show and show. $mysql_select2="mysql_query(".$mysql_show.") or die(mysql_error())"; } //if allowed to show. if($mysql_select2){ //while it and while($data=mysql_fetch_assoc($mysql_select2)){ //show it. echo $data; } } ?> Hello all, I have a php login project that I am almost finished with. I have users in a table and I can login with the users BUT when I click the login button I get
Notice: session_start(): A session had already been started - ignoring in E:\xampp\htdocs\PHP_Login\index.php on line 53 Warning: Cannot modify header information - headers already sent by (output started at E:\xampp\htdocs\PHP_Login\index.php:53) in E:\xampp\htdocs\PHP_Login\index.php on line 60 When I click the refresh button I get what I am supposed to get and I am logged in to the dashboard.
<?php error_reporting(E_ALL); ini_set("display_errors", "1"); // Initialize SESSION session_start(); // Check if logged in ifso sent to Welcome.php if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true) { header("Location: php/welcome.php"); exit; } // Include config mySQL require_once "php/config.php"; // Define all variables and initialize them as 'empty' $username = $password = ""; $usernameerror = $passworderror = ""; // Process form data when submitted if($_SERVER["REQUEST_METHOD"] == "POST") { // Check if username is empty. if(empty(trim($_POST["username"]))) { $usernameerror = "Please enter a username"; } else { $username = trim($_POST["username"]); } // Check if password is empty. if(empty(trim($_POST["password"]))) { $passworderror = "Please enter a password"; } else { $password = trim($_POST["password"]); } // Validate credentials. if(empty($usernameerror) && empty($passworderror)) { // Prepare a SELECT statement. $sql = "SELECT userid, name, username, password FROM users WHERE " . "username = :username"; if($stmt = $pdoConn->prepare($sql)) { // bind variables to the prepared statement as parameters $stmt->bindParam(":username", $param_username, PDO::PARAM_STR); // Set parameters $param_username = trim($_POST["username"]); // Attempt to execute prepared statement. if($stmt->execute()) { // Check if username exists if so check password. if($stmt->rowCount() == 1) { if($row = $stmt->fetch()) { $id = $row["userid"]; $username = $row["username"]; $password_hashed = $row["password"]; $name = $row["name"]; if(password_verify($password, $password_hashed)) { // Password correct start new session session_start(); // store data in SESSION variables $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; $_SESSION["name"] = $name; //Redirect to welcome.php header("Location: php/welcome.php"); } else { // If password INCORRECT error msg $passworderror = "Password was <b>Incorrect!</b>"; } } } else { $usernameerror = "No account was found."; } } else { echo "Error something went wrong, incorrect execution "; } } // Close prepared stmt unset($stmt); } // Close connection unset($pdoConn); } ?>
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 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 } ?> 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']; } } } ?> 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 <!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 don't know how to solve this error;
Parse error: syntax error, unexpected '$db' (T_VARIABLE)
code:
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"> |