Session Value Not Working - php

I was trying to make a one page script with the action set to server php self but when running the script even after I type in the right password I am given "You Must Supply a Password". Am I doing this right. Please let me know my mistake
login.php
<?php
$pass = 'defense6';
if(isset($_POST['submit'])){
if(($_POST['password'] == $pass)) {
$_SESSION['password'] = md5($_POST['password']);
header('Location: index.php');
} else {
echo 'Password Invalid';
}
}
else {
echo 'You must supply a password.'.$_SESSION['password'] ;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Password: <input name="password" type="password" /><br/><br/>
:
<input type="submit" name="submit" value="Login" style="float:right;" />
<br/>
<p></p>
</form>
index.php
<?php
$pass = 'defense6';
if($_SESSION['password'] == md5($pass)) {}
else {header('Location: login.php');}
?>

You need to add seesion_start() on every page you use session.
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.

Add session_start() at the beginning of the pages that will help to maintain the session across requests.

Related

Make a form sticky with php session

I am trying to create php multipage forms, and I use PHP sessions for this purpose.
However, when there is an error in user input and I want the form to ask user to fill in the form again with correct inputs, the forms field will not hold the data that the user has already put in so the user has to start things all over again.
How to make forms sticky with php session?
Thanks
My code is as bellow
<?php
// Session starts here.
if (!isset($_SESSION)) session_start();
?>
<form action="registration.php" method="post">
<center><h8>Please create your user name and password</h8></center>
<div class="imgcontainer">
<img src="phone.gif" alt="Welcome" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required value="<?php if(isset($_POST['username'])) echo $_POST['username'];?>">
<label><b>Password</b></label>
<input type="Password" placeholder="Enter Password" name="password" required>
<label><b>Confirm Password</b></label>
<input type="Password" placeholder="Confirm Password" name="confirm" required>
<span id="error" width=100%>
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo "<error>".$_SESSION['error']."</error>";
unset($_SESSION['error']);
}
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
?>
</span>
<br>
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</div>
and the registration php contains
<?php
if (!isset($_SESSION)) session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['username']))
{
if (($_POST['password']) === ($_POST['confirm']))
{
foreach ($_POST as $key => $value)
{
$_SESSION['post'][$key] = $value;
}
}
else
{
$_SESSION['error'] = "Password does not match with Confirm Password.";
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
header("location: createlogin.php"); //redirecting to first page
}
}
Something like this:
<input name="var" value="<?= isset($_SESSION['var']) ? $_SESSION['var'] : null ?>" />
Try the other way around. Linking the form-action to the current page, and if all fields are valid; redirect it to the next page (registration.php). This way you'd still have all the post-data, you can process everything that needs to be saved in the session- and you can redirect after all of the logic is done.
My two cent would be keep the same page to validate the content and for the form.
You can include other PHP files from a single page depending on if the form is valid.
This way, you keep the same $_POST between both pages and don't need to store the posted data in a session variable.
Otherwise, if you want to keep the same architecture, you need to use the $_SESSION variables instead of the $_POST ones in your input value, such as the answer by delboy.
Replace:
<?php if(isset($_POST['username'])) echo $_POST['username'];?>
With:
<?php if(isset($_SESSION['username'])) echo htmlspecialchars($_SESSION['username']); ?>
^ Note: htmlspecialchars is used to prevent a reflected XSS if the users enters " as username.
The problem is, your data posted to registration.php, so you can't get the posted value in your original file. You are trying to use $SESSION but that's not recommended, and not right. Your whole solution is wrong.
Forget about session and separated files, put everything to registration.php file together.
You can check if user posted or not with $_SERVER['REQUEST_METHOD'] variable.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print 'Something just posted';
}
PS: Don't forget secure the password before you store it! :)

How to start and destroy session properly?

So, I have:
index.php(login and register form, welcome page, etc.)
login.php(it's a simple login verify php file, which executes when user press submit on index.php),
home.php (the site where the user redirects after logged in correctly)
logout.php(the reverse of login.php, redirects the user to index.php and destroy the session (I thought..)
The problem is, I can get at home.php, even before I sign in correctly, anytime.
I put start_session() on every page that needs $_SESSION variable, and put session_destroy() in logout.php as well.
So here are the php files' codes:
index.php
<body>
<?php
require_once('config.php');
if ($maintanance) {
echo "Az oldal karbantartás alatt van.";
}
else if ($db_conn_error) {
echo "Something went wrong according to database connection.";
}
else {
include('reg.php');
include('./templates/header.php');
?>
<section>
<form id="login_form" action="" method="POST">
<h2>Already a member? Sign in!</h2>
<p>Username: <input type="text" name="username"></p>
<p>Password: <input type="password" name="password"></p>
<input type="submit" name="login_submit" value="Sign In">
<?php include 'login.php'; ?>
</form>
<form id="reg_form" action="" method="POST" onsubmit="return validation();">
<h2>Sign up Now!</h2>
<p>Username: <input type="text" name="username" placeholder="min. 5 characters">
<span id="user_error"></span>
</p>
<p>Password: <input type="password" name="password" placeholder="min. 8 characters"></p>
<p>Password again: <input type="password" name="password_again"></p>
<p>E-mail: <input type="email" name="email" size="30"></p>
<p>Date of birthday:
<input type="number" name="bd_year" min="1950" max="2016">
<input type="number" name="bd_month" min="1" max="12">
<input type="number" name="bd_day" min="1" max="31">
</p>
<input type="submit" name="reg_submit" value="Sign Up">
</form>
</section>
</body>
</html>
<?php } ?>
login.php
<?php
include 'config.php';
if (isset($_POST["login_submit"]))
{
$username = $_POST["username"];
$password = $_POST["password"];
$query = "SELECT username, hashed_password FROM users WHERE username = '$username';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rows_num = mysqli_num_rows($result);
$password_match_error_message = false;
if ($rows_num == 0) {
echo "<p class='login_error_msg'>This user doesn't exist!</p>";
}
else {
$password_match = password_verify($password, $row['hashed_password']);
if (!$password_match) {
echo "<p class='login_error_msg'>Wrong password!</p>";
}
else {
session_start();
$_SESSION["user"] = $username;
header("Location: home.php");
}
}
}
?>
home.php
<?php
session_start();
if (isset($_SESSION["user"])) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Spookie - Social Network</title>
<link rel="stylesheet" type="text/css" href="./css/style.css">
</head>
<body>
<?php
include './templates/header.php';
?>
<?php } else { echo "You are not logged in!"; } ?>
</body>
</html>
logout.php
<?php
session_unset($_SESSION["user"]);
session_destroy();
header("Location: index.php");
?>
I know, it's hard to see what's really going on through the codes, the login works, but the session is not really.
The problem: I type in and home.php is always reachable, despite the fact I'm not logged in. The logout.php doesn't destroy the session or even the session couldn't start.
Thank you very much for your help! :)
The problem is in logout.php.
You should also claim session_start() to ensure you CAN remove the $_SESSION["user"] variable.
There may be other problems as I cannot see the whole code. Correct me if I am wrong.
Take a look at the another answer which explains the typical way to set up session variables
According to this manual: http://php.net/manual/en/function.session-destroy.php
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.
The manual link has a full working example on how to do that. Stolen from there:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
session_start() will start session.
session_destroy() will destroy session.
For setting session data you could do this.
`
$_SESSION['is_logged_in'] = true;
`
FOR CHECKING EXISTENCE OF SESSION or to check if user is logged in
`
If(isset($_SESSION['is_logged_in'] ) {}
else {
//redirect to login page
}
`

Bug using PHP Sessions (Two Log On screens)

In the application I'm developing I'm having a bug where I direct my browser to my app's index.php, and is then properly redirected to login.php if there is no current session. My problem is that after I type in my correct details on login.php and click submit, I am linked to another login.php screen (instead of returning to index.php with an active session) and required to put in my details again. The first screen has the same CSS formatting as index.php, while the second screen doesn't.
After entering my details on the second screen and clicking login, the sessions seem to function normally. Also, many times I will be presented with one logon screen, ill login and the user's correct Home screen data will be displayed (which requires successful queries from the login data), but if I navigate away from index.php to another screen that requires an active session, it will present the unformatted login.php screen.
If I logout, navigate to a different non-restricted page, and attempt to log back in again within the same browser session, the logon functions correctly with only one screen.
Here are snippets from the relevant files:
index.php
<?php
include_once 'db_functions.php';
require_once 'access.php';
if (isset($_POST['action'])) {
if (userIsLoggedIn()) {
header('Location: http://www.myapp.com/index.php'); //prevents users from having to confirm form resubmission if they refresh the page
}
}
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
login.php:
login.php
<body>
<h1>Log In</h1>
<?php
if (isset($loginError)) {
echo $loginError;
}
?>
<form action="" method="post">
<div>
<label for="email">Email: <input type="text" name="email" id="email" /> </label>
</div>
<div>
<label for="password">Password: <input type="password" name="password" id="password" /></label>
</div>
<div>
<input type="hidden" name="action" value="login" />
<input type="submit" value="Log in" />
</div>
</form>
</body>
access.php:
<?php
function userIsLoggedIn() {
if (isset($_POST['action']) and $_POST['action'] == 'login') {
if (!isset($_POST['action']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '') {
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$email = $_POST['email'];
$password = $_POST['password'];
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
return TRUE;
}
else {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout') {
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn'])) {
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password']);
}
}
function databaseContainsAuthor($email, $password) {
include_once './db_functions.php';
$db = new DB_Functions();
$result = $db->accountExists($email, $password);
return $result;
}
?>
Any help would be greatly appreciated!
UPDATE:
Error logs are showing multiple occurances of this error:
PHP Notice: A session had already been started - ignoring session_start() in /home3/monitot5/public_html/app/access.php on line 17
Access.php line 17:
if (databaseContainsAuthor($email, $password)) {
session_start(); //LINE 17
$_SESSION['loggedIn'] = TRUE;
What you should do is to use
session_start();
at the beginning of access.php file and don't use this function any more.
You should also completely change login of your access.php file. The first thing you should always do in this file is checking if there's a valid session for this user. Now you check it at the end of file and probably earlier you clear it because you unset session if there are no $_POST data.
In addition you shouldn't also use password in your session. It's rather very insecure. You should simple store login for your system when user filled in form valid username/email and password and unset it if user has logged out.
Sorry, but I won't write the whole code for you. You should simple look at some examples of code in Google to check how to handle user login/logout in PHP.

Login Page Username and Password cannot be posted (PHP)

Username and password not appear on Page 2.PHP although I post it to Page2.PHP
Page1.PHP
<form name="form1" method="post" action="Page2.php">
<input type="text" name="txtLogin">
<input type="password" name="txtPWD">
<input type="submit" name="btnSub" value="go">
</form>
Page2.PHP
<?php
if(isset($_REQUEST['txtLogin']))
{
session_start();
$_SESSION['login']=$login;
}
if(isset($_SESSION['login']))
header('Location: detail.php');
else
header('Location: index.html');
?>
put this on page2.php
if(isset($_POST['txtLogin']) && isset($_POST['txtPWD']))
{
//get values & do other scripts like saving values on sessions
$user = $_POST['txtLogin'];
$pass = $_POST['txtPWD'];
echo $user.'<br>'.$pass;
}
else
{
//event here
}
The problem is here:
$_SESSION['login']=$login;
You are using the $login variable, but it isn't actually being set anywhere.
A few lines further up, we see that the login name is actually in $_REQUEST['txtLogin'], not $login. So you should be using that.
$_SESSION['login']=$_REQUEST['txtLogin'];
Hope that helps.
Check settings: enable_post_data_reading, request_order, variables_order, gpc_order on http://www.php.net/manual/en/ini.core.php

How to stop else showing as default on basic PHP login script

I am using PHP to build a very basic login script. However, the else from the ifelse statement shows by default before the user has even clicked log in.
Before the user has even tried to login they are greeted with this:
Warning: Cannot modify header information - headers already sent by (output started at /home/madhous3/public_html/dev/admin/index.php:12) in /home/madhous3/public_html/dev/admin/login.php on line 13
Sorry, please try again.
How do I stop this? However, if the user enters the details correctly, they are directed to the right page.
Code
index.php
<?php
include("login.php");
?>
<h1>Admin Area Login</h1>
<form method="post" action="login.php">
Username<input type="text" name="username" />
Password<input type="text" name="password" />
<input type="submit" name="log_in" value="Log In" />
</form>
login.php
<?php
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
}else{
header("location:index.php");
echo "Sorry, please try again.";
}
?>
Try removing the include("login.php") from index.php.
Instead, you should redirect back to index.php from your login.php with a flag specifying that the user entered the wrong information (if they failed the login).
index.php
<?php
if(isset($_REQUEST['fail'])) {
echo 'Login failed.';
}
?>
<h1>Admin Area Login</h1>
<form method="post" action="login.php">
Username<input type="text" name="username" />
Password<input type="text" name="password" />
<input type="submit" name="log_in" value="Log In" />
</form>
login.php
<?php
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
} else {
header("location:index.php?fail=1");
}
?>
OK, so what's happening is that in index.php you're including login.php at the start. At that time it imports everything from login.php. Since you're including it, the script is going to run.
At the load of the page index.php, the script on login.php starts. It defines those variables $username_inputted & $password_inputted as null, since the POST hasn't happened yet. Then the if block checks, finds null variables, then the else block fires since the variables aren't equal to the expected login info because they're null.
Therefore the echo fires and is displayed on the screen before anything is POSTed.
Nav_nav's solution should work well, since the only time the 'bad login' echo will be displayed is if someone entered something into the input fields, I just wanted to give you a rundown of the algorithm's reason for messing up.
try this
if (!empty($_POST['username']) && !empty($_POST['password'])) {
//define input vars
$username_inputted = $_POST['username'];
$password_inputted = $_POST['password'];
if($username_inputted == 'admin' && $password_inputted == 'password'){
header("location:login_success.php");
}else{
header("location:index.php");
echo "Sorry, please try again.";
}
}
First get rid of the header('location:login.php'). You can't send a header if you've already started sending any HTML to the browser. And if it did work, you'd get an endless loop of reloads.
Then:
You could check for $_POST ['submit'] and if it doesnt exist then don't show them the try again message.

Categories