Session Handling in PHP 5 - php

i've a problem with php session handling that i can't explain to myself.
I'm studying php from scratch, and i can't figure out how to mantain a session live:
This is my index page, where a user can login or register to the database visiting the right page, and then come back to see if he's logged in:
Code:
Index
<?php session_start(); ?>
Register
Login
<?php
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin'];
?>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
else
{
echo "Please Register or Login";
}
?>
In fact this work, because when i come back from login.php it says, "Logged as: Admin"
But when i click on the link to get the login page, or register page again from the index page, i should get the same message, "Logged as...", but the session appear to be closed instead. :(
here's login.php:
<?php
session_start();
include "dbConnect.php";
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin']; // IT NEVER SHOW THIS MESSAGE
}
if(isset($_POST['submit']) &&(trim($_POST['submit']) == "Login"))
{
if(!isset($_POST['user']) || $_POST['user']=="")
{
echo "Attenzione inserire l'username.";
}
elseif(!isset($_POST['pwd'])||$_POST['pwd']=="")
{
echo "Attenzione inserire la password.";
}
else
{
$u = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));
$u = str_replace(" ","_",$u);
$p = trim(filter_var($_POST['pwd'], FILTER_SANITIZE_STRING));
$p = sha1($p);
$istance = new dbHandle;
$istance->connect();
$data = $istance->query("SELECT * FROM login WHERE username_login = '$u' AND password_login = '$p'");
if(mysql_num_rows($data) == 0)
{
echo "Failed";
echo "<a href='index.php' target='_self'> Go Back </a>";
}
else
{
echo "Logged";
$res = $istance->getdata($data);
$_SESSION['login'] = $res->id_login;
$_SESSION['nlogin'] = $res->username_login;
echo "<a href='index.php' target='_self'> Go Back </a>";
}
}
}
else
{
?>
Login
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...
<input name="user" type="text" size="20" required="required"/>
...
<input name="pwd" type="password" size="20" required="required"/>
...
<input type="submit" name="submit" value="Login"/>
</form>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
$istance->disconnect();
?>
When i come back using the link above "Go Back" to the index page, it shows Logged as...
but when i come back here again, it does not.
So i assume my session were destroyed automatically? but why?
Thanks, i appreciate your help.
I forget to say that PHP.ini has
session.cookie_lifetime
set to "0"
Thanks

You are calling unset($_SESSION['login']) many times. It removes your login:
<form method="post" action="<?php unset($_SESSION['login']) ?>">
Try this:
<form method="post" action="index.php">
<input type="button" name="logOut" value="LogOut" />
</form>
<? if (isset($_REQUEST['logOut'])){ session_destroy(); } ?>

unset the session like below
if(isset($_REQUEST['logOut']))
{
unset($_SESSION['login']);
}

You check for if(isset($_SESSION['login'])).
If that results in true, you do <form method="post" action="<?php unset($_SESSION['login']) ?>">
Note the unset($_SESSION['login']) part - after that, if(isset($_SESSION['login'])) will return false.

Session overview :
<?php
// Always Start our session
session_start();
$_SESSION['username'] = 'Saurabh Singh';
$username = $_SESSION['username'];
echo $username;
if(isset($_SESSION['username']))
{
Do your action
}
else
{
echo "Please Register or Login";
}

I don't think the session has been destroyed!
I would start by first removing all the empty lines between the opening tags for php and the
session_start().
Test it again and you could add the line
error_reporting(E_ALL);
below the session_start to see if any error messages are echo(ed) back to you.
In your PHP.ini what
session.cookie_lifetime = 0
means is that the session remain active so long as the browser stays open. It's only destroyed when the browser is closed.
I hope this helps

Related

Sessions variable unseen in multiple pages

I don't understand the thing with sessions in php. It says that after you start a session, the session variable are stored and can be seen in multiple pages.But in my pages that are not seen. For example I have my index.php page where I start the session_start(). Then I click a button to login and if everything is ok it should redirect me to profile.php page where I print the session email. But it doesn't recognize my session variable.My code:
if($_POST['actiune'] == 'login'){
$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
if ($verify) {
header("Location: index.php?page=profile");
}
else {
header("Location: index.php?page=login&msg=PleaseRegister");
}
}
profile.php
echo $_SESSION['username'] ; die();
Any help?
UPDATE:
profile.php
<?php
session_start();
echo $_SESSION['username'] ;
?>
<div id="profile">
<p id="welcome">Welcome :<?php echo $_SESSION['username']; ?></p>
<?php
if ($_SESSION['avatar'] == ""){
?>
<img src = "http://placehold.it/400x200/0000ff/&text=Upload a picture" alt =""/>
<?php
}
else if ($_SESSION['avatar'] != ""){
?>
<img src="avatars/<?php echo $user['file'];?>">
<?php
}
?>
<p id="modifyPf"> Modify</p>
<p id="reset"> Reset password</p>
<p id="articlePf"> Article page</p>
<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="actiune" value="avatar">
<input type="hidden" name="id" value="<?php echo $user['id'];?>">
<p><label for="avatar">Upload an avatar:</label></p>
<p><input type="file" name="avatar" id="fileToUpload"></p>
<p><input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/></p>
</form>
You need to call session_start(); in profile.php also.
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.
Update
<?php
if(!isset($_SESSION))
{
session_start();
}
if (isset($_SESSION['username'])){
?>
<div id="profile">
<p id="welcome">Welcome :<?php echo $_SESSION['username']; ?></p>
<?php if ($_SESSION['avatar'] == ""){ ?>
<img src = "http://placehold.it/400x200/0000ff/&text=Upload a picture" alt =""/>
<?php
}
else if ($_SESSION['avatar'] != ""){
?>
<img src="avatars/<?php echo $user['file'];?>">
<?php
}
?>
<p id="modifyPf"> Modify</p>
<p id="reset"> Reset password</p>
<p id="articlePf"> Article page</p>
<form action="action.scripts.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="actiune" value="avatar">
<input type="hidden" name="id" value="<?php echo $user['id'];?>">
<p><label for="avatar">Upload an avatar:</label></p>
<p><input type="file" name="avatar" id="fileToUpload"></p>
<p><input id ="button" class="btn btn-primary" type="submit" name="button" value="Send"/></p>
</form>
</div>
<?php
}
else {
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
}
?>
Index.php
<?php
session_start();
if($_POST['actiune'] == 'login'){
$email = $_POST['email'];
$_SESSION['username'] = $email;
$password = $_POST['password'];
$pass = getPassword($email);
$verify = password_verify($password, $pass);
if ($verify) {
header("Location: index.php?page=profile");
}
else {
header("Location: index.php?page=login&msg=PleaseRegister");
}
}
else {
echo 'POST actiune is not login';
}
?>
You need session_start() at the top of every page request - exactly one time per request. It doesn't just create the session; it's required for every request in which you want to use the session. From the docs:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

i am trying to practice a simple session code in my house in xamp

but some how the page is not showing any error message. also it is not redirecting to the page where i want to redirect it after successful login. i want the login page to be redirected at home page and show the message and when the logout link is clicked the page again come back to the login page
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_post["unametxt"]; ?>" />
<label>Password</label><input type="password" value="<?php echo $_post["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_post["sbt"]))
{
if($_post["unametxt"]== "debarun" && $_post["password"]=="1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_post["unametxt"];
$_SESSION["passwd"]=$_post["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
and it is my home page script:
<?php
session_start();
if(!isset($_SESSION["login"])){
session_destroy();
header('location:login.php');
}
else{
echo "Welcome".$_SESSION["uname"]."<br/>"."your password is".$_SESSION["passwd"];
}
?>
<html>
<body>
<form action="" method="post">
Logout
</form>
</body>
</html>
please
tell me why it is not working??
Add name attribute in your password element. Because of this, it cannot fetch from $_POST array and your condition will always fail.
Try this,
<label>Password</label><input type="password" name="password" value="<?php echo $_post["password"]; ?>" />
First thing $_post must be up letter case like this $_POST then you forgot to specify name="password" to password input field
take a look
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
?>
<?php
if($_REQUEST["logout"]=='yes'){
unset($_SESSION["login"]);
}
?>
<html>
<body>
<form action="" method="post">
<label>Username</label><input type="text" name="unametxt" value="<?php echo $_POST["unametxt"]; ?>" />
<label>Password</label><input type="password" name="password" value="<?php echo $_POST["password"]; ?>" />
<input type="submit" name="sbt" value="Login">
</form>
<?php
if(isset($_POST["sbt"]))
{
echo $_POST["password"];
if($_POST["unametxt"] == "debarun" and $_POST["password"] == "1234")
{
$_SESSION["login"]="yes";
$_SESSION["uname"]=$_POST["unametxt"];
$_SESSION["passwd"]=$_POST["password"];
header('location:home.php');
}
else
{
echo "Please enter correct credentials";
}
}
?>
</body>
</html>
Put all those validation code at the top. Nothing should be sent to the browser before redirecting. Not even an empty line.
Also, make the L in location capital
header("Location: home.php");

How to make a page accessible only after log in

here is my login page:login.php
<?php
require_once('connectvars.php');
//start the session
session_start();
//clear the error message
$error_msg="";
//If the user isn't logged in ,log them in
if(!isset($_SESSION['user_id']))
{
if(isset($_POST['submit']))
{
//connect to database
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$user_username=mysqli_real_escape_string($dbc,trim($_POST['username']));
$user_password=mysqli_real_escape_string($dbc,trim($_POST['password']));
if(!empty($user_username)&&!empty($user_password))
{ $query="select user_id,username from gyan_userdata where username='$user_username'and password=SHA('$user_password')";
$data=mysqli_query($dbc,$query);
if(mysqli_num_rows($data)==1)
{
$row=mysqli_fetch_array($data);
$_SESSION['user_id']=$_row['user_id'];
$_SESSION['username']=$_row['username'];
setcookie('user_id',$_row['user_id'],time()+(60*60*24*30));
setcookie('username',$_row['username'],time()+(60*60*24*30));
$home_url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/index2.php';
header('Location:'.$home_url);
}
else
{
$error_msg ='<p>Your username or password combination is incorrect</p>';
}
}
else
{
$error_msg= 'You must enter a username and password to log in';
}
}
}
$page_title='Log In';
require_once('header.php');
if(empty($_session['user_id']))
{
echo '<p class="error">'.$error_msg.'</p>';
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username:</label>
<input type="text" id="username" name="username" /><br/>
<label for="password">Password:</label>
<input type="password" id="password" name="password" /><br/>
<input type="submit" value="Log in" name="submit" />
</form>
<?php
}
else {
// Confirm the successful log-in
echo '<p class="login">You are logged in as ' . $_SESSION['username'] . '.</p>';
}
?>
I want to make my index.php accessible only after login
I have added this code to my index.php page
here is my index page:index.php
<?php
session_start();
if(!isset($_SESSION['user_id']))
{
echo '<p>Please Login to continue Log In</p>';
exit();
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index_style.css" />
</head>
<script src="dropdown.js">
</script>
</head>
</html>
but even after logging in I'm again asked to log in.
I think your issue is that you're not setting $_SESSION['user_id'] properly
$row=mysqli_fetch_array($data);
$_SESSION['user_id']=$_row['user_id'];
Should be
$row=mysqli_fetch_array($data);
$_SESSION['user_id']=$row['user_id'];
Note that $_row became $row
Firstly, $_session that's a superglobal. It must be in uppercase.
http://php.net/manual/en/language.variables.superglobals.php
Then, you're using $_row but fetching the array using $row=mysqli_fetch_array($data);
so that will fail.
Use $_row=mysqli_fetch_array($data); if you want to keep what you've already coded.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
and or die(mysqli_error($dbc)) to mysqli_query() which would have caught the syntax error.
Sidenote: Error reporting should only be done in staging, and never production.

echo to a div rather than a blank page

I am using this code to create a secure log in page in PHP. I got it from http://girlswhogeek.com/tutorials/2006/creating-a-secure-php-login-page.
<?php
$username = "user";
$password = "pass";
$randomword = "bibblebobblechocolatemousse";
if (isset($_COOKIE['MyLoginPage'])) {
if ($_COOKIE['MyLoginPage'] == md5($password.$randomword)) {
?>
CONTENT HERE
<?php
exit;
} else {
echo "<p>Bad cookie. Clear please clear them out and try to login again.</p>";
exit;
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['name'] != $username) {
echo "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>";
exit;
} else if ($_POST['pass'] != $password) {
echo "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>";
exit;
} else if ($_POST['name'] == $username && $_POST['pass'] == $password) {
setcookie('MyLoginPage', md5($_POST['pass'].$randomword));
header("Location: $_SERVER[PHP_SELF]");
} else {
echo "<p>Sorry, you could not be logged in at this time. Refresh the page and try again.</p>";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<fieldset>
<label>
<input type="text" name="name" id="name" /> Name
</label>
<br />
<label>
<input type="password" name="pass" id="pass" /> Password
</label>
<br />
<input type="submit" id="submit" value="Login" />
</fieldset>
</form>
It works really well, however, when there is a mistake in the log in information, it switched to a blank page and echos out a message saying the log in information is wrong. I was wondering if there were a way to have it echo to a div on the page with the inputs. I tried putting the relevant echo messages inside a div but it didn't work. I must admit that I don't even know why it's going to a blank page.
Also, is this the best way to do it or is there a way to make it more secure?
Thanks for any rendered assistance.
Benny.
There are 2 issues:
The exit in your code stop the execution of the page so after 'echo-ing' your message, the page stops
If you want to display in a div, set the message in a variable and display it in the div code
Here is an example of your code, re-worked a bit (you might want to adjust):
<?php
$message = NULL;
if (isset($_COOKIE['MyLoginPage'])) {
if ($_COOKIE['MyLoginPage'] == md5($password . $randomword)) {
?>
CONTENT HERE
<?php
exit;
} else {
$message = "<p>Bad cookie. Clear please clear them out and try to login again.</p>";
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['name'] != $username) {
$message = "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>";
} else if ($_POST['pass'] != $password) {
$message = "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>";
} else if ($_POST['name'] == $username && $_POST['pass'] == $password) {
setcookie('MyLoginPage', md5($_POST['pass'] . $randomword));
header("Location: $_SERVER[PHP_SELF]");
} else {
$message = "<p>Sorry, you could not be logged in at this time. Refresh the page and try again.</p>";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<fieldset>
<label><input type="text" name="name" id="name" /> Name</label>
<br />
<label><input type="password" name="pass" id="pass" /> Password</label>
<br />
<input type="submit" id="submit" value="Login" />
</fieldset>
<?php
if (isset($message)) {
echo "<div>" . $message . "</div>";
}
?>
</form>
Are you putting your entire content, including the <html> tags where it says CONTENT HERE?
The only thing that should go there is the secure content, not the whole page. Your boilerplate html, <html><head><title>title</title></head><body> ... </body></html> should go around the whole block of code you posted. The contents of CONTENT HERE only display with a successful login, so anything that isn't secure shouldn't be shown there.
Here's an alternative implementation of a PHP page locker I wrote a long time ago, that may make this more clear.</shameless plug>
You're echoing the result of the login if it fails, but not displaying a page with it. If you want to display the login failed page within your sites design already, I'd recommend sending them back to the login page with the error message. For example:
header("Location: http://website.com/loginpage.php?failed=1");
and then in the login page's code:
if ($_GET['failed'] == '1') echo "Failed to login. Please try again.";
This way if the login fails, they will be sent back to the login page with the error message.

Logout problem /session not destroyed

I am having a problem when trying to login.. below is my code for the login
<?php
session_start();
include("functions.php");
connecttodb();
if(!empty($_SESSION['loggedin']) && !empty($_SESSION['username']))
{
echo "already logged in";
header("refresh:3; url=main.php");
}
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql="SELECT * FROM admin WHERE admin_username ='".$username."' AND admin_password= '".$password."'";
$result=mysql_query($sql) or die(mysql_error());
echo $sql;
if(mysql_num_rows($result) == 1)
{
$row = mysql_fetch_array($result);
$acc = $row['account'];
$_SESSION['username'] = $username;
$_SESSION['account'] = $acc;
$_SESSION['loggedin'] = 1;
echo "<h1>Success</h1>";
echo "<meta http-equiv='refresh' content='=2;panel.php' />";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Please click here to try again.</p>";
}
}
else
{
?>
<form method="post" action="login.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
My logout file
<?php
$_SESSION = array();
session_unset();
session_destroy();
echo "Logged Out !";
header("Location:login.php");
?>
The problem is that when i try to logout the session is not destroyed. When it redirects to the login page it says that im already logged in. How can i completely destroy the session when the users clicks on logout?
change your logout to the following:
<?php
session_start(); # NOTE THE SESSION START
$_SESSION = array();
session_unset();
session_destroy();
// echo "Logged Out!";
// Note: Putting echo "Logged Out!" before sending the header could result in a "Headers already sent" warning and won't redirect your page to the login page - pointed out by #Treur - I didn't spot that one.. Thanks...
header("Location:login.php");
exit(); # NOTE THE EXIT
?>
The session_start() is always require for each page when dealing with sessions.
Make sure you exit() the page when using header() with Location as the page will continue to execute.
I think you forgotten the session_start() before $_SESSION = array(); in your logout script

Categories