PHP - Logout Session Message
I was wondering if there is away to set a logout message when you are using sessions
this is my code <?php session_start(); if($_SESSION[auth] = "yes") { session_unset(); session_destroy(); header( "Location: index.php" ); exit(); } else { if ($_SESSION[auth] != "yes") { header( "Location: index.php" ); $_SESSION['error'] = "please login!"; exit(); } } ?> Similar Tutorialshow to logout using session in proper way ? can you give me the code I am having problems understanding the reason for why the user has to click logout twice, here's the bulk of the code: <?php ini_set('display_errors',0); require_once 'header.html'; require_once 'db.functions.php'; require_once 'config.php'; $database = dbConnect($host, $username, $password, $database); // should output 1 or nothing at all! if($database == true) { // now connected? // carry on with logic of outputting the blog contents: $result = entries("SELECT * FROM entries"); printf("<table>"); while($row = mysql_fetch_array($result)) { printf(" <tr> <td>%s</td> <td>%s</td> </tr> <tr> <td colspan=\"2\">%s</td> </tr> ", $row[2], $row[4], $row[3]); } printf("</table>"); printf("\n\n"); session_name("jeremysmith_blog"); session_start(); if(array_key_exists('login',$_SESSION)) { if($_SESSION['login'] == 1) // change this to correspond with session on the login.php script { printf("<p>Welcome %s</p> <p>To logout, click <a href=\"index.php?action=logout\">here</a></p> ",$_SESSION['username']); } } else { printf("<p>You are not logged in, please click <a href=\"login.php\">here</a> to login.</p>"); } } else { printf("\n<p id=\"error\">Could not connect to database, please try again later.</p>"); } // init the logout script? if(array_key_exists('action',$_GET)) { if($_GET['action'] == 'logout') { // log user out of the system: unset($_SESSION['login']); unset($_SESSION['username']); session_destroy(); } } printf("\n"); // just for output format! require_once 'footer.html'; Why does the user have to click logout twice, have I missed anything? Any helps appreciated thanks. Hi, I'm having a problem with contact form not display message log. It does successfully send, but fails to get the session variables. Where did I go wrong? This is my contact form code <?php include('includes/ui.php'); head('Contact Us','contactpage.css'); ?> <script src="js/SpryValidationTextField.js" type="text/javascript"></script> <link href="js/SpryValidationTextField.css" rel="stylesheet" type="text/css" /> <script src="js/SpryValidationTextarea.js" type="text/javascript"></script> <link href="js/SpryValidationTextarea.css" rel="stylesheet" type="text/css" /> <div class="section"> <h3>Contact Us</h3> <div class="scontent"> <?php /* ------------------------------------------------- Displays success/error message --------------------------------------------------*/ if ($_SESSION['message']!='') { ?> <div id="log"><?php echo $_SESSION['message']; ?></div> <?php unset($_SESSION['message']) ?> <?php } ?> <?php /* ------------------------------------------------- Contact Form --------------------------------------------------*/ ?> <p><em>If you have any questions, feel free to fill the form below:</em></p> <form action="sendmail.php" method="post"> <label>Name:</label> <span id="sprytextfield1"> <input type="text" class="istext" name="name"/> <span class="textfieldRequiredMsg">This field is required.</span></span> <label>Email:</label> <span id="sprytextfield2"> <input type="text" class="istext" name="email"/> <span class="textfieldRequiredMsg">This field is required.</span></span> <label>Message</label> <span id="sprytextarea1"> <textarea name="message"></textarea> <span class="textareaRequiredMsg">This field is required.</span></span><br/> </span> <label>Enter the code:</label> <img src="includes/captcha.php" /><span id="sprytextfield3"> <input class="input" type="text" name="norobot" /> <span class="textfieldRequiredMsg">This field is required.</span></span><br/> <input type="submit" class="btn" value="Send"/><span class="tab2em"></span><input type="reset" class="btn" value="Reset"/> </form> <div id="bible"> </div> <span class="clear"></span> <br class="clear"/> </div> </div> </div> <script type="text/javascript"> <!-- var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1"); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2"); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1"); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3"); //--> </script> <?php footer(); ?> This is my sendmail.php <?php session_start(); if (md5($_POST['norobot']) == $_SESSION['randomnr2']) { // here you place code to be executed if the captcha test passes $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $name = filter_var($name, FILTER_SANITIZE_STRING); $email = filter_var($email, FILTER_SANITIZE_EMAIL); $message = filter_var($message, FILTER_SANITIZE_STRING); require_once('includes/class.phpmailer.php'); $mail = new PHPMailer(); $body = "Someone with the ".$name." and an email address of ".$email." send you the ff message: ".$message; $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "mail.example.com"; // SMTP server $mail->SMTPAuth = true; // enable SMTP authentication $mail->Host = "mail.example.com"; // sets the SMTP server $mail->Port = 26; // set the SMTP port for the GMAIL server $mail->Username = "example@example.com"; // SMTP account username $mail->Password = "thepassword"; // SMTP account password $mail->SetFrom('example@example.com', 'Me'); $mail->Subject = "Message sent from site contact form"; $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($body); $address = "tosomeone@yahoo.com"; $mail->AddAddress($address, "Richard"); if(!$mail->Send()) { $_SESSION['message'] = "Failed sending, please try again later"; } else { $_SESSION['message'] = "Message sent"; } } else { // here you place code to be executed if the captcha test fails $_SESSION['message'] = "Invalid code"; } header('Location: http://example.com'); ?> Thanks in advance I am so glad someone told me about putting in the error_reporting ALL because I was not sure why my id for members was not picking up on the next pages. Can someone let me know how I can fix this I thought it automatically picks it up and sets it to private pages for each member. Notice: Undefined index: id in /home/ebermy5/public_html/login.php on line 25 <?php session_id(); session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Welcome</title> </head> <body> <?php /* Program: New_member.php * Desc: Displays the new member welcome page. Greets * member by name and gives a choice to enter * restricted section or go back to main page. */ error_reporting(E_ALL); ini_set("display_errors", 1); $firstname = ''; include('Connections/connect_to_mysql.php'); $result = mysql_query("SELECT firstname FROM `Members` WHERE id='{$_SESSION['id']}'"); $row = mysql_fetch_array($result); if ($firstname == ''){ //condition, is name equal to lower case firstname notice we use == and not = echo "Welcome, $firstname"; } else { //so incase the condition is not as expected echo "Sorry you are not $firstname"; } ?> <p>Your new Member accounts lets you enter the members only section of our web site. You'll find special discounts, a profile of matches, live advise from experts, and much more.</p> <p>Your new Member ID and password were emailed to you. Store them carefully for future use.</p> <div style="text-align: center"> <p style="margin-top: .5in; font-weight: bold"> Glad you could join us!</p> <form action="profile.php" method="post"> <input type="submit" value="Enter the Members Only Section"> </form> <form action="index.php" method="post"> <input type="submit" value="Go to eBermylove Main Page"> </form> </div> </body> </html> I am getting an error message. But the program works Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\Exam_Online\try.php:3) in C:\xampp\htdocs\Exam_Online\Staff_login_process.php on line 4 Wrong Username or Password my code is <Html> <?php //session_start(); include 'Staff_login_process.php'; MYSQL_CONNECT(localhost,'root','') OR DIE("Unable to connect to database"); @mysql_select_db(Examination) or die( "Unable to select database"); ?> <body> <form action="try1.php" method="post"> <?PHP $query=("SELECT * FROM User u, User_X_Subject us, Subject s WHERE u.Use_Name = '{$_SESSION['username']}' AND u.Use_ID= us.Use_ID AND s.Sub_ID=us.Sub_ID"); $result=mysql_query($query) or die ("Unable to Make the Query:" . mysql_error() ); echo "<select name=myselect>"; while($row=mysql_fetch_array($result)){ echo "<OPTION VALUE=".$row['Sub_ID'].">".$row['Sub_Name']."</OPTION>"; } echo "</select>"; ?> <input type="submit" value="submit"/> </form> </body> </html>
Hi! The file login.php and the config file containing the db connection are in the model folder and the login_view is in view folder. I am trying to make a login form am display some error messages to the user, but I don't get the error messages. Can you help me figure it out? PS: the connection to the db works fine! Thx! LOGIN.PHP <?php //start the session session_start(); foreach (glob("model/*.php") as $filename) { include $filename; } //form defaults $error["alert"]= ""; $error["user"]= ""; $error["pass"]= ""; $input["user"]= ""; $input["pass"]= ""; if(isset($_POST["submit"])) { //process form if($_POST["username"] == "" || $_POST["password"] == ""){ //display errors if($_POST["username"] == ""){$error["user"] = "required";} if($_POST["password"] == ""){$error["pass"] = "required";} $error["alert"] = "Please fill in the required fields"; //get the values for the username and password $input["user"]= $_POST["username"]; $input["pass"]= $_POST["password"]; include("../views/login_view.php"); } }else{ include("../views/login_view.php"); } LOGIN_VIEW.PHP <?php session_start(); foreach (glob("model/*.php") as $filename) { include $filename; } ?> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <!--author:starttemplate--> <!--reference site : starttemplate.com--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="keywords" content="unique login form,leamug login form,boostrap login form,responsive login form,free css html login form,download login form"> <meta name="author" content="leamug"> <title>Unique Login Form | Bootstrap Templates</title> <link href="/styles/style.css" rel="stylesheet" id="style" type="text/css"> <!-- Bootstrap core Library --> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!-- Google font --> <link href="https://fonts.googleapis.com/css?family=Dancing+Script" rel="stylesheet"> <!-- Font Awesome--> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> </head> <body> <!-- Page Content --> <div class="container"> <div class="row"> <div class="col-md-offset-5 col-md-4 text-center"> <h1 class='text-white'>Login Form</h1> <form action ="" method="POST"> <div class="form-login"></br> </br> <?php if($error["alert"] != ''){ echo "<div class='alert'>".$error["alert"]."</div>"; } ?> <div> <input type="text" name ="username" id="userName" class="form-control input-sm chat-input" placeholder="Username" value= "<?php echo $input['user'] ?>" required/> <?php echo $error['user'] ?> </div> </br></br> <input type="text" name ="password" id="userPassword" class="form-control input-sm chat-input" placeholder="Password" value= "<?php echo $input['password'] ?>" required/> <div class="error"> <?php echo $error['pass'] ?> </br></br> <div class="wrapper"> <input type="submit" class="btn btn-primary" value="submit"> </div> </div> </div> </form> </div> </div> </body> </html> Edited October 28, 2020 by Alexa Hello all, I'm new to PHP and new to this forum (although I have benefitted from your help already -cheers!). However, this time I cannot find the answer I need/recognise/understand.. I have a form and want to conduct tests on each field returning an error message as a session variable if the test fails. The test will be different for some of the fields, and the error message is specific to each field. If there is an error in any one of the fields I want to be redirected to a failure page where all of the error messages are displayed, otherwise I am sent on to another page. I have already written and tested a function to sanitise the incoming form data, so that's not a problem - it's just how to loop through and test. I can guess that there are many ways to do this but I need to understand why one option is better than another, and follow the syntax used (it's all part of my steep learning curve) The approach I have thought to use is to create an array holding the field name, the test and the message, then loop through using foreach, applying the array values into the test and creating the error message....but it's not working for me. The other method is to declare a variable $Stop='No' and if the loop identifies an error, part of the output is to change this to 'yes' and through that redirect to the error page. I'd really welcome your advice and tuition....cheers.. my code so far is... Code: [Select] $Stop='No'; $StaffPassCheck=sanitisealphanum($_POST['PasswordCheck']); $Errors[0]['value']= sanitisealphanum($_POST['FirstName']); $Errors[0]['message']='Please re-enter your name'; $Errors[0]['test']=($StaffFname=""); $Errors[1]['value']= sanitisealphanum($_POST['Surname']); $Errors[1]['message']='Please re-enter your surname'; $Errors[1]['test']=($StaffSname=""); $Errors[2]['value']= sanitisealphanum($_POST['Post']); $Errors[2]['message']='You must select an option'; $Errors[2]['test']=($StaffPost="Select Value"); $Errors[3]['value']= sanitisealphanum($_POST['Username']); $Errors[3]['message']='You must select an option'; $Errors[3]['test']=($StaffUser=""); $Errors[4]['value']= sanitisealphanum($_POST['Password']); $Errors[4]['message']='Please re-enter your password'; $Errors[4]['test']=($StaffPass=""); $Errors[5]['value']= sanitisealphanum($_POST['PasswordCheck']); $Errors[5]['message']='Sorry, your passwords do not match'; $Errors[5]['test']=($StaffPass===$StaffPassCheck); foreach ($Errors as $key => $Value){ if ( $Errors['test']=true ){ $Stop='Yes'; return $_SESSION[$key]=$Value['message']; } } if ($Stop='Yes'){ header('Location.test.php'); die(); }else{ header('Location.indexp.php'); } this is not working Code: [Select] <?php session_start(); $username = $_SESSION['username']; echo mysql_query("UPDATE members SET online='0' WHERE username='$username' AND online='1'"); session_destroy(); echo "You've been logged out. <a href='index.php'>Click here</a> to return."; ?> what im trying to do is change the online mysql data from 1 back to 0 as i want to show when a user is on and off line can anyone help Hi, How logout is executed after 15 min. if does not hit or refresh any page. Code: [Select] <?php session_start(); $_SESSION['is_logged_out'] = 1; if($_SESSION['is_logged_out'] ==1) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('You had been successfully signed out')</SCRIPT>"); session_unset(); session_destroy(); header("Location:chatframe.php"); } ?> I got this error Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\login\logout.php:6) in C:\xampp\htdocs\login\logout.php on line 9 which mistake im put? When writing a logout script in PHP what steps should i take? Should i: 1.) unset all session vars like: unset($_SESSION["var1"]); unset($_SESSION["var2"]); or calls session_unset(); 2.) destroy session cookie like: setcookie(session_name(), "NULL", time()-60, $params['path'], $params['domain'], $params['secure'], isset($params['httponly'])); 3.) finally destroy the session data by calling session_destroy(); or maybe just only unset the session vars - that is making only the first step? I'm asking because I've seen many logout scripts that doesn't involve these 3 steps (i most cases doing only the first one as i stated) Thx. for help. Hi, im new here Need some help. I have a database which contains users, and for every user i have logged_in value which is 1 if user is logged in and 0 if not. I use this so that user can be logged in only once. When user clicks on logout link i set logged_in on 0. My problem is when browser closes logged_in for current user is not set to 0, and after that user can't login because my site thinks he is already logged in. is there some way I can call some function when browser exits or any other solution? please help Hey guys, me again. A few of you were helping me with my login script, which I did finally get working. I am having one small problem though. Upon clicking the logout link, it does not re-direct back to the login page, it just stays blank. I have pasted my code from my logout.php file for reference. Thanks in advance for your help! Logout.php code <?php session_start(); session_destroy(); { header("location: login.php"); } exit(); ?> Hi there I have this problem with a button that should destroy sessions and then redirects to login page when clicked, pointing to this method: Code: [Select] public function logout(){ $this->logged_in = false; session_start(); session_unset(); session_destroy(); redirect_to("login.php"); } the function is called as bellow: Code: [Select] <form> <input id="logout" name="logout" type="submit" value="logout" onClick="<?php $session->logout(); ?> " /> </form> which is available on a page called index.php, which is the default page where you'll be directed to when logged in or just registered. unfortunately when I'm supposed to be to this page and before even clicking on the button, the function just does the work and redirects to the login page!!!.....any help please [/color][/size] For some reason my logout is not working properly. I searched other forum posts and read some tutorials but I still have an issue. Do this to create session: Code: [Select] $_SESSION['username'] = $row['username']; setcookie('username', $row['username'], time() + (60 * 60 * 24 * 5)); Do this to log out the user Code: [Select] session_start(); session_unset(); $_SESSION = array(); setcookie(session_name(), '', time() - 3600); session_destroy(); setcookie('username', '', time() - 3600); Above all else I am trying to end the $_SESSION['username'] Thank you all Hi, I am having a bit of problem with my login/logout script. When user is logged in I want the script to show logout and if they are not login I want the script to show login. The problem is even when the user is logged in it says "you must be logged in Click here to login " here is the script Please help Code: [Select] <?php session_start(); $_SESSION['username'] = $_POST['username']; if ($_SESSION['username']) echo "Welcome, ".$_SESSION['username']."!<br><a href='logout.php'>Logout</a>" ; else die("you must be logged in <a href='Login.php'>Click here to login</a>"); ?> what did I do wrong in this script ? Thanks Hi, Just wondered if anyone could help Ive been following this tutorial: http://net.tutsplus.com/tutorials/php/user-membership-with-php/ Ive got a simple membership system working now, but just wondering about the login / login links that i currently have. The login link is currently hard coded like so: Code: [Select] <ul id="menu"> <li id="active"><a href="index.html">Home</a></li> <li><a href="About.html">About</a></li> <li><a href="Contact.php">Contact</a></li> <li class="end"><a href="login.php">Login</a></li> </ul> and same for the logout: Code: [Select] <ul id="menu"> <li id="active"><a href="index.html">Home</a></li> <li><a href="About.html">About</a></li> <li><a href="Contact.php">Contact</a></li> <li class="end"><a href="logout.php">Logout</a></li> </ul> But the problem is, when i go to the about us page for example it will still display the login which really it should have logout. Could anyone offer some assistance please Hello, I'm currently storing a timestamp of the users last activity in my database in which if that hasn't been updated for 15 minutes (for testing doing 2 minutes) I want it to log the user out. I have been trying different things but they all seem to log me out even though they shouldn't be. Example of something I've tried $Online = time() - 120; if ($CheckOnline['lastaction'] < $Online){ header("Location: Logout.php"); session_destroy(); } Am I going at this the wrong way.? If I do $Online < $CheckOnline['lastaction'] it keeps me logged in but never logs me out.
Any help would be brillaint.
Thank you! I based this off some other pages read, and think I'm doing this wrong or it's just not connecting. Code: [Select] Here's the database table: CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, username VARCHAR(30) NOT NULL UNIQUE, password VARCHAR(64) NOT NULL, salt VARCHAR(3) NOT NULL, PRIMARY KEY(id) ); Ando far I have index.php with my login form <form name="login" action="login.php" method="post"> Username: <input type="text" name="username" /> Password: <input type="password" name="password" /> <input type="submit" value="Login" /> </form><br />Would you like to <a href="register.php">register?</a></center> Then I have my actual login on login.php (header.php includes website's main image as well as session_start(): <?php include('header.php'); $username = $_POST['username']; $password = $_POST['password']; //connect to the database here $username = mysql_real_escape_string($username); $query = "SELECT password, salt FROM users WHERE username = '$username';"; $result = mysql_query($query); if(mysql_num_rows($result) < 1) //no such user exists { header('Location: login.php'); die(); } $userData = mysql_fetch_array($result, MYSQL_ASSOC); $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) ); if($hash != $userData['password']) //incorrect password { header('Location: login_form.php'); die(); } else { validateUser(); //sets the session data for this user } //redirect to another page or display "login success" message ?> then I have my register php on register.php: <?php include('header.php'); //retrieve our data from POST $username = $_POST['username']; $pass1 = $_POST['pass1']; $pass2 = $_POST['pass2']; if($pass1 != $pass2) header('Location: register_form.php'); if(strlen($username) > 30) header('Location: register_form.php'); $hash = hash('sha256', $pass1); function createSalt() { $string = md5(uniqid(rand(), true)); return substr($string, 0, 3); } $salt = createSalt(); $hash = hash('sha256', $salt . $hash); $dbhost = 'localhost'; $dbname = 'mygame'; $dbuser = 'root'; $dbpass = ''; $conn = mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbname, $conn); //sanitize username $username = mysql_real_escape_string($username); $query = "INSERT INTO users ( username, password, salt ) VALUES ( '$username' , '$hash' , '$salt' );"; mysql_query($query); mysql_close(); header('Location: login.php'); ?> and lastly the register form: <center><form name="register" action="register.php" method="post"> Username: <input type="text" name="username" maxlength="30" /> Password: <input type="password" name="pass1" /> Password Again: <input type="password" name="pass2" /> <input type="submit" value="Register" /> </form></center> I am getting the errors: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/testing/login.php on line 13 Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/testing/config.php:1) in /Applications/XAMPP/xamppfiles/htdocs/testing/login.php on line 15 Could someone explain why this is happening? is it possible to update data in mysql when a user clicks logout? |