PHP Session Destroy on Log Out Button - php

I'm currently working on a site that has a log-in (username and password) - The password protection is done by the operating system within the web server at folder level called a Realm within the OS. For now this will have to do, until we figure out a proper PHP log in system.
The code below, is based on a previous question on the stack overflow.
I'm using 3 files (See code snippets at the bottom).
The process is:
- Click Log In button on index.php
- Enter username and password to access authenticate index file.
- Click log out button, which references the logout.php file - it SHOULD clear the cache and return the user to the top level index.
It doesn't 'destroy the session' in the sense that you're not asked to re-enter the password when prompted to, which is essentially what I want to happen.
My minimal knowledge of php leaves me a little bit stumped here.
index.php (top level file with log in button)
<?php 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>Test</title>
</head>
<body>
Log In Btn
</body>
</html>
authenticate/index.php (This folder is password protected - contains the index file with the log out button which links to the logout.php file)
<?php 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>Log out</title>
</head>
<body>
Log Out Btn
</body>
</html>
authenticate/logout.php
<?php
session_start(); //to ensure you are using same session
session_destroy(); //destroy the session
header("location:/index.php"); //to redirect back to "index.php" after logging out
exit();
?>

The folder being password protected has nothing to do with PHP!
The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...
Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):
login.php:
<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
$_SESSION['logged_in'] = true;
header('Location: /index.php');
}
else
{
?>
<form method="POST">
Username: <input name="user" type="text"><br>
Password: <input name="pass" type="text"><br><br>
<input type="submit" value="submit">
</form>
<?php
}
index.php
<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
?>
<p>here is my super-secret content</p>
<a href='logout.php'>Click here to log out</a>
<?php
}
else
{
echo 'You are not logged in. Click here to log in.';
}
logout.php:
<?php
session_start();
session_destroy();
echo 'You have been logged out. Go back';
Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.
Hope this helps you understand what's going on.

First give the link of logout.php page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.

if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
The if block of the Global array $_GET check if the logout var is set in the url
Then, the session destroy function is called
And then, the global session array value username is removed/deleted the header function will redirect you back to login page

if(isset($_POST['logoutButtonName'])) {
session_destroy();
unset($_SESSION['nameOfSessionToBeDestroyed']);
header('location:login.php');
}
Header should then redirect you to your desired page

Related

Include a php page to password protected the other pages content and showing the user logging in info in the header.php

I would like to include a PHP page to protect every single page and after you login, it would show your username on the top right corner,
also it limits the only data that login user had provided such as his CV and personal info but without seeing other users info.
the structure will be the same as the previous post
index.php (include header.php, content.php and footer.php)
The title on the header.php will be changed menu after user login
Thank you.
Regards
Andy
Well if you want a script to ensure that it would be something like this:
first: Assuming you're not using design patterns and it is a php basic project with an archetype like " scripts(folder) css(folder) js(folder) index.php header.php and footer.php". lets create "security.php".
<?php
session_start(); //starting session to acces to it
if(empty($_SESSION["username"])){// if there's no data username in session
header("location: ./login.php"); //go and take them out of here!
}
?>
Now you have "security.php" ready you just have to include it to your protected pages and create a "login.php" page.
Ex: For including security.
<?php
//#mySecurePage
include "security.php";
//My Page Content Code or event header code if you want validation after loading anything (Best)
?>
Second: Create a Login page like.
<?php
if(!empty($_POST["username"]) && !empty($_POST["password"])){// if all data from login was sent
if($_POST["username"] == "me" && $_POST["password"] == 1234){//your validations here
session_start();//start session to acces it
$_SESSION["username"] == $_POST["username"];//allocate username
header("location: ./securedPageHere.php");//forward to a securedPage
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Login Page</title>
</head>
<body>
<form class="" action="" method="post"><!-- action is empty to send data to same page (login)-->
<input type="text" name="username" value="" placeholder="username">
<input type="password" name="password" value="" placeholder="password">
<input type="button" name="login" value="Login">
</form>
</body>
</html>
Now we're almost done, just need to load username at your menu bar
Third: Load username at menu bar. Just add the value accesing session (remember if you have loaded "security.php" you've already started session
<div><?php print($_SESSION["username"]); ?></div>
Now to use the Logut Button you have to destroy session, so add a listener to it and then just execute a script like:
<?php
unset($_SESSION); //clear session array
session_destroy(); //Destroy session
?>
Hope it helps you.
EDIT: to limit data accessed just use the username (best id) data from the login verified data saved at session array :).

PHP Session Variable created by Form Submission not persisting

I have Opera 12.15 on XP with cookies enabled running on XAMPP and localhost. There is no .htaccess.
1) I can't understand why the following session variable does not persist in Opera whilst it does in the other mainstream browsers. With Opera only, if you revisit the page (via a link) after the Form has been accepted, the session variable has gone and the Form is displayed again. It's okay (i.e. the variable persists) if I just refresh the page.
2) I also have a secondary question, as you can see below I have opened a php tag and started an 'if' statement, then closed the php tag, entered some html, opened a new php tag, closed the 'if' and finally closed the second php tag. Is this valid code, I was originally taught to echo the html within the 'if' and just have one set of php tags? The former is easier and works, I saw it used elsewhere.
Thanks in advance.
<?php
// Turn on error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Opera Session Variable</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
// create a test variable to confirm other session variables outside of Form are persisting
$_SESSION['test'] = 'Test';
// function to print session variables
function print_array( $_SESSION )
{
echo '<pre>$_SESSION<br />' . "\n";
print_r($_SESSION);
echo "</pre>\n";
}
// process the submitted form
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if (isset($_POST['formaccept'])) {
$_SESSION['formaccepted'] = $_POST['formaccept'];
}
}
// print the session variables
print_array( $_SESSION );
// only display the form if it has not previously been accepted in this session
if (!isset($_SESSION['formaccepted'])) {
?>
<p><b>This parargraph should only display if the form has not been accepted in the current session.</b></p>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="formaccept" value="Accept" />
</form>
<?php
}
?>
</body>
</html>
Must be the way opera handles the cache, I can't see any error with your code.
As for your second question, that syntax works but is not usually recommended, since it makes the layout dirty being full of snippets.

Issues With PHP Session

I am trying to create a very simple session between 3 php pages as: index.php ,validate.php and target.php
index.php
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start A Session</title>
</head>
<body>
<h1>Welcome to Heaven</h1>
<form method="POST" action="validate.php">
Your Name: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
and validate.php as:
<?php
session_start();
$err="Not Allowed";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: heaven.php");}
else
{echo $err; }
?>
and finally target.php as
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start Email with PHP</title>
</head>
<body>
<h1>Welcome to Targer <?php echo $_SESSION['uid'] ?></h1>
<img src="session.jpg">
</body>
</html>
Now my questions are:
How come user still can get access to target page while I have already set a session between pages(according to my understanding of sessions the target page must NOT be accessible unless the correct seesion value has been submitted but I can get access to page by clicking on page link in wamp index list! with echoing the $err; ! )
I tried to validate the $_SESSION value by using the isset() but it did'nt go through! can you please let me know how I can modify the validate.php using the isset() instead of if(($_POST['name']) == $_SESSION['uid']) comarison?
Can you please let me know how I can merge two (index.php and validate.php) in one page? I mean how I can validate the session inside the index.php and reduce the files two index and target? In this case I need to handle the wrong logins inside the index page.
Finally, can you please let me know how I can assign the value to $_SESSION from user input? I mean instead of having a hard coded part like $_SESSION['uid'] = 'test'; let the session value start with user input! I know this looks meaningless here but I would like to get idea on creating captcha in same index page
Thanks for your time in advance
This should work properly and just with 2 files. You could even compress it to 1 file, if you really want so (it's much harder to understand), ask for it and I can make it.
index.php:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start A Session</title>
</head>
<body>
<h1>Welcome to Heaven</h1>
<form method="POST" action="heaven.php">
Your Name: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
And the other file, heaven.php
<?php
session_start();
if (!empty($_SESSION['uid'])&&$_POST['name']==$_SESSION['uid'])
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Start Email with PHP</title>
</head>
<body>
<h1>Welcome to Targer <?php echo $_SESSION['uid'] ?></h1>
<img src="session.jpg">
</body>
</html>
<?php
}
else
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Access denied</title>
</head>
<body>
Sorry, you have no permission to access this page.
</body>
</html>
<?php
}
?>
'Validation' is just to display the desired message if the strings match or to display a 'you cannot see this page' if they don't match.
The !empty() needs to be set. Else, imagine what would happen if someone visited the 'heaven.php' page without going first to index.php. You'd compare 2 empty strings! So it would be validated. The alternative is to put $_SESSION['uid'] = 'test'; at the beginning of heaven.php also.
I didn't really answer your questions in order (and in the 2nd one I cheated as I put 2nd and 3rd file together instead of 1st and 2nd), but my code should cover all your problems. For the last part, it's simply $_SESSION['uid']=$_POST['name']; , but it'd be a no sense to do it while validating user. The validation must come from somewhere, generally from a mysql database.
Please start to accept answers to your questions if valid (below the up/down button).
1) What do you mean by assigning correct session value? "heaven.php" is a file which is accessible by anyone if you don't check for access rights in that file.
2) Not sure what you mean. If you need to check if two variables exist and match, you need something like if ( (isset($_POST['name']) && isset($_SESSION['uid'])) && (($_POST['name']) == $_SESSION['uid']) )
3) If there's no need to reduce files to minumun, it's a good idea to keep validating, form processing etc. function in their respective files. If you want to valide session and form values within "index.php" you can do so by first checking if the values exist and then do to them whatever you like. (Like in the 2 above.)
4) You can assign user inputted values for variables by using forms. It's what you are doing with your form currently. In you process file/function you do something like:
if(isset($_POST['submit']){
$_SESSION['uid'] == $_POST['name'];
}
The example above is very simplified.
Finally. You aren't really validating anything, you just check if two values match. Validating means that you make sure value meets the standard(s) specified, for example user submitted value is an integer when it should be an integer (when inserted into database or used some other manner). I think you should see some tutorials about form processing and user input validation before creating anything that's intended in production environment.

Cannot save array to session, comes up empty

If you can get this simple SESSION VARIABLES example to work, I'll hug you!
I can't get Session Variables to work at all on my site. I'm running php5, on Windows 7, using Chrome browser.
Here's the send page:
<?php
session_start();
$red='red';
$blue='blue';
$green='green';
$SESSVARS=array($red,$blue,$green);
$_SESSION['USERVARS']= $SESSVARS;
?>
<p>Set Sessionvars</p>
<form action="SessVarCheck.php" method="post">
<input name="Submit" type="submit">
</form>
Here's the result page:
<?php
session_start();
echo "val 1:".$_SESSION['USERVARS'][0];
echo "val 2:". $_SESSION['USERVARS'][1];
echo "val 3:". $_SESSION['USERVARS'][2];
?>
<!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>SessVarCheck.php</title>
</head>
<body>
The Result page
</body>
</html>
I get empty on all three echos.
Any ideas would be welcome!
Make sure that the call to session_start() happens before any page contents are output, on both pages. (See "Note" section here)
(I assume you may already know about this, but given that I don't see a "<html>" on the send page I thought there might be more to that script. Also, I don't know how sensitive this requirement is - just the spaces before the php tag might be enough to be a problem.)
Try a few things:
1) do a var_dump($_SESSION) on your results page, to see what the raw contents of the session are
2) Verify that the sessions are working correctly. Add echo "SessionID: " . session_id(); to both scripts, somewhere AFTER the session_start() calls. If you don't get the same session ID on each page, you're getting a new session each time and it's most likely a cookie problem.

PHP Login questions

So I am wanting to create a login script for my page using php and MySQL. I have been searching the internet for a good tutorial on all the information about this but it seems most of them just give a script and say here you go. The Problem is that I need more information about sessions and cookies and stuff. Does anyone know of a good place to learn about this stuff?
You must to understand that every time you use the session_start(); function, you are creating a new session on your server or if its already created it makes a reference, so this identify every visitor by browser, and at the same time you create this session the server sets the cookie variable on the headers with a variable called PHPSESSID this variable has a hash with the id of your session.
In PHP you have a pre-defined global variable called $_SESSION this variable can be use it to store data such a flag for your login, something like this.
$_SESSION['login'] = true;
so you can use this variable to check if the user is already logged, every time you need to show something just allowed to registered users.
Honestly I don't know of any place for what you want cause I learned it by myself. Because really it's easy.
The basic principle behind all that is to verify that the entered login information is correct (checking it via your BL and DA, if you know what I'm talking about) and then store some arbitrary info about the user in the $_SESSION variable like$_SESSION['name'] = 'guest' and then write a simple statement at the beginning of every page that requires login to check the contents of the $_SESSION array and if it's not set, redirect to another page an so on...
That's it! :D
Hope I could answer what you were looking for! ;-]
EDIT:
Here is a simple login page:
<?php
session_start(); //required if you want to use the $_SESSION array
$username = $_REQUEST['txtUsername']; //storing the value of the "txtUsername" text box in the form sent by client after the form has been submited
$password = $_REQUEST['txtPassword']; //same as $username
if (isset($username) && isset($password))
{
/*
* this section depends on the implementation of your BL and DA layers.
* assume that my BL selects a member by it's username and returns an array
* containing his/her info
*/
require_once('mybl.php'); //assume that my BL tier is implemented in the "mybl.php" file
MyBL $bl = new MyBL();
$queryResult = $bl->selectByUsername($username);
//authenticating user
if ($queryResult['username'] == $username && $queryResult['password'] == $password)
{
//the user has been authenticated and can proceed to other pages available for members only
/*
* i'm storing the user's username in the session so that I could refer to it in other pages
* in case I want to update/modify database tables for this specific user.
*/
$_SESSION['username'] = $username;
//store anything else you want for the current user:
$_SESSION['name'] = $queryResult['name']; //for welcome prompt
header('Location: welcome.php'); //redirecting the user
}
else //in case of wrong username/password
{
$message = "Incorrect username/password";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>LoginPage</title>
</head>
<body>
<form method="post" action="login.php">
<table style="border: 1px dashed">
<tr>
<td>Username:</td>
<td><input name="txtUsername" type="text" />
</tr>
<tr>
<td>Password:</td>
<td><input name="txtPassword" type="password" />
</tr>
<tr>
<td colspan="2" align="center"><input name="btnSubmit" type="submit" value="Login" />
</tr>
</table>
</form>
<span style="color: red;"><?php echo $message; ?> </span>
</body>
</html>
The welcome page:
<?php
session_start();
//checking to see if the user is logged in
if (!isset($_SESSION['username']))
header('Location: login.php'); //the user is not logged in, he/she is redirected to the login page.
/*
* Basically you might want to put this code at the beginning of every page that requires
* logging in. This way a user that hasn't logged in can't see the contents of the page
* and you don't have to worry about extra checking and conditions that could raise errors
* due to empty "$_SESSION" array.
*/
?>
<!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>Login successful</title>
</head>
<body>
Login successfull!<br />
Welcome <?php echo $_SESSION['name']; ?>
</body>
</html>
What exactly are you looking for regarding sessions and cookies?
Make sure you use http://php.net/manual/en/index.php
But if you give more info we can help point you in a much better direction
EDIT:
This looks like a pretty comprehensive tutorial with all the functionality you will need:
http://www.evolt.org/node/60265
Here are some references that might help:
PHP session documentation
Wikipedia article on what HTTP cookies are
PHP cookie documentation (Note that you will rarely need to use both sessions and cookies for authentication alone.)
My authentication PHP authentication with multiple domains and subdomains, not so secured, will be updated later.
Learn about PDO for database manipulation. That doesn't just go for login scripts but for PHP in general. It will go a long way to help you write secure programs.
I think the problem you're running into is that a secure login script brings into play a number of features of MySQL and PHP, which is more than a lot of the tutorials want to get into.
There's a pretty good tutorial here, but it's set up so it shows how to build the login routine both in PHP4 and PHP5, so watch the numbered headings and make sure you're using only the files applicable to your version of PHP. Be sure to check out the section on encrypting passwords. These days, you'll definitely be better off doing that. The nice thing about the tutorial is that it includes comments for each step, so you will know what they're doing and can search for more info if you need it. The other thing you can do is post back here with a portion of your script if you need explanation about a particular part.

Categories