data in $_POST across multiple pages - php

I am new to PHP and I wrote scripts for simple login. When successfully login and click the link "back to login", I was not able to have the previous login username filled. I know using $_COOKIE['username'] for the value of username works, but I am wondering why $_POST['username'] does not work? Thank you!
login.php
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(!empty($_COOKIE['lastVist'])){
echo "your last login time:".$_COOKIE['lastVist'];
setcookie("lastVist",date("Y-m-d H:i:s"),time()+24*3600*30);
}else{
echo "you first login time:";
}
setcookie("username", $_POST['username'], time()+24*3600*30);
?>

A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer and unlike post as it has information for specific request sent by user.
When we use an application, we open it and do some changes, then we close it. This is much like a Session, so to preserve information we have per session global array in php $_SESSION.
A session is started with the session_start() function and values are stored in simply associative array fashion $_SESSION['key'] = $value;.
login.php
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="./loginProcess.php" method="post">
Username: <input type="text" name="username" value="<?php echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : ''; ?>"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="send">
</form>
</body>
</html>
loginProcess.php
<?php
session_start();
echo "welcome, ".$_POST['username'].", login success!!";
echo "<br/><a href='login.php'>Back to login</a><br>";
if(isset($_SESSION['lastVisit'])){
echo "your last login time:".$_SESSION['lastVisit'];
}else{
echo "you first login time:".$_SESSION['lastVisit'];
$_SESSION['lastVisit'] = date("Y-m-d H:i:s", time());
}
$_SESSION['username'] = $_POST['username'];
?>

In principle, in loginProcess.php, if you would have used, for example, a form with a hidden input containing the username value, then this value would have been readable in the login.php - after clicking the "back to login" anchor:
Welcome <?php echo $_POST['username']; ?>, login success!!
<br>
<form id="backToLoginForm" action="login.php" method="post">
<input type="hidden" name="username" value="<?php echo $_POST['username']; ?>" />
<a href="#" onclick="javascript:document.forms['backToLoginForm'].submit();">
Back to login
</a>
</form>
But you really shouldn't do what you want to do. E.g. to go back to the login.php without logging-out first - at least. If you would do it and complete other credentials - in the login.php - as the ones used for the first login, then you would still need to logout the previous user before validating the new credentials. This would be a bad management of active session, cookies, etc.
More of it, the autocomplete of login credentials is a job for the password managers, or of the form fillers, not of your own code - unless it's part of the validation process of the currently given login credentials (see the code example below).
So, as an alternative to your approach, my suggestion would be the following login.php code. No need for a loginProcess.php page anymore:
<?php
session_start();
// Operations upon form submission.
if (isset($_POST['submit'])) {
// Validate the username.
if (!isset($_POST['username']) || empty($_POST['username'])) {
$errors[] = 'Please provide the username.';
}/* Here other password validations using elseif statement. */
// Validate the password.
if (!isset($_POST['password']) || empty($_POST['password'])) {
$errors[] = 'Please provide the password.';
} /* Here other password validations using elseif statement. */
// Get the posted data.
$username = $_POST['username'];
$password = $_POST['password'];
if (!isset($errors)) {
/*
* Check the given credentials in the db. If the user doesn't exist, add an error:
*/
// $errors[] = 'Wrong credentials. Please try again.';
/*
* ... else add only the user id - fetched from db - to session.
* Don't add other user related details to session. If, in other pages,
* you want to use other user details, fetch them there using the user id.
*/
if (!isset($errors)) {
$_SESSION['userId'] = 43;
// Redirect to the welcome page.
header('Location: welcome.php');
exit();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Login</title>
<style type="text/css">
.form-control {
margin-bottom: 10px;
}
label {
display: inline-block;
min-width: 80px;
}
.messages {
margin-bottom: 20px;
}
.error {
color: #c00;
}
button {
padding: 5px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<form action="" method="post">
<div class="form-control">
<label for="username">Username:</label>
<input type="text" id="username" name="username" value="<?php echo isset($username) ? $username : ''; ?>">
</div>
<div class="form-control">
<label for="password">Password:</label>
<input type="password" id="password" name="password" value="<?php echo isset($password) ? $password : ''; ?>">
</div>
<button type="submit" id="submit" name="submit">
Login
</button>
</form>
</body>
</html>

Related

Login implementation in PHP

Suppose, I have two pages login.php and index.php. In index.php I have two buttons Login and register.After clicking the buttons ,the user is directed to login.php.
If I want to implement a login functionality using PHP, something related to facebook such that the if a user has logged in before, then it bypasses the index page once the username and password are set and directly lands into the login page. Is $_SESSION a proper way of doing it.
For example:
<?php
session_start();
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Ayu</title>
</head>
<body>
<?php if (isset($_SESSION["user"])) { ?>
<h1>Hi <?php echo $_SESSION["user"]; ?></h1>
Logout
<?php } else { ?>
<h1>Login</h1>
<?php echo (isset($_GET["error"])) ? '<p>You idiot!</p>' : ""; ?>
<form action="new-user.php" method="post">
<div>
<label>
<strong>Username</strong>
<input type="text" name="username" />
</label>
</div>
<div>
<label>
<strong>Password</strong>
<input type="password" name="password" />
</label>
</div>
<input type="submit" value="Log In" />
</form>
<?php } ?>
</body>
</html>
In the login functionality, I am setting the $_SESSION values
<?php
session_start();
if (count($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
unset($_SESSION["user"]);
header("Location: ./?error");
}
?>
Yes using and creating ($_SESSION) session is the correct way to check logged in users.
$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.
Check for session on very top of a page, if found redirect to index else to login page.
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
Refer this simple login example using my sql in php Here
EDIT
As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:
<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>
Html Form in the above code will only be shown if a user is logged in else it will be hidden.
Yes, Session is best way to implement the same. You can use the below php code to solve your problem
<?php
session_start();
if (!empty($_POST))
if ($_POST["username"] == "ayu" && $_POST["password"] == "shee") {
$_SESSION["user"] = "Ayushi";
header("Location: ./");
} else {
if($_SESSION["user"]!=''){
unset($_SESSION["user"]);
}
header("Location: ./?error");
}else{
/* Write code for form */
}
?>

Simple PHP login not working

I'm very new to PHP and I'm trying to build a webpage with a login page. I think I understand it but my login page isn't working even though its very basic.
This is my file structure at the moment:
http://imgur.com/a/zVcPK
This is the idx (index):
<?php
error_reporting( E_ALL );
ini_set( "display_errors", 1 );
include 'templates/header.php';
if(!isset($_SESSION['logged'])){
include 'controller/login.php';
}else{
if($_SESSION['logged'] == true){
include "controller/navigation.php";
}else{
include "idx.php";
}
}
include 'templates/footer.php'
?>
This is the login.php template:
<?php
$out = "<form method='POST' action='idx.php'>
<p>Login:</p>
<label>Username:</label><input type='text' name ='username' required />
<label>Password:</label><input type='password' name'password' required />
<input type='submit' value='submit' name=submit'/>
</form>";
echo $out;
This is the login.php controller:
<?php
include "view/login.php";
if(isset($_POST['submit'])){
$urn=$_POST['username'];
$pwd=$_POST['password'];
$user = new user($urn);
$worked = $user->authenticate($urn, $pwd);
if($worked == true){
$_SESSION['logged']=true;
$_SESSION['username']=$urn;
header('Location: controller/navigation.php');
}
else
{
echo('Error');
}
}
?>
This is the user model:
<?php
class user
{
private $username;
function __construct($username)
{
$this->username=$username;
}
function authenticate($username, $password)
{
if ($username == 'tim' && $password == 'ttt') {
return true;
} else {
return false;
}
}
}
?>
I'm just trying to get the form to take in the users details, check that they are "tim" and "ttt" and if so return a true value which will prompt the controller to change the header URL to navigation.php controller which in turn shows the navigation.php view which will just be a list of links. For some reason though whenever I hit submit nothing happens, it just stays on the login page.
I know this is a pretty basic thing to do but I've been stuck on it for a couple of days now and I've watched hours and hours of videos on it and read dozens of pages explaining how MVC works but can't get this simple thing done. Please can somebody tell me whats going wrong.
Make sure you start the session on every page you want to get or set session variables.
session_start()
It should be as simple as that, and it threw me for a loop for quite a while.
Have you considered using an MVC framework? They are very helpful for keeping everything tidy and organized, as well as providing a library of helpful functions and classes. CodeIgniter is a great and easy to use framework that is super lightweight. Laravel is a lot more invovled and is better suited for large scale projects.
Change this:
<input type='password' name'password' required />
This:(You missed = name='password')
<input type='password' name='password' required />
And dont forget to add session_start() at the very top of your page.
I will share you my sample PHP login page setup.
it has 3 pages, index, admin, logout
index.php: Creates a form asking username and password, once correct username pssword given (here admin, password) it will create a new session "login". Once logged in it will redirect to the admin.php $validuser ensures previous login is true or not.
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if (isset($_POST["sub"]))
{
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if (!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if ($validUser)
{
header("Location: /admin.php");
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<center>
<h1>Login</h1>
<table>
<form name="input" action="" method="post">
<tr>
<th>
<label for="username">Username</label>
</th>
<th>
<input type="text" value="" id="username" name="username" />
</th>
</tr>
<tr>
<th>
<label for="password">Password</label>
</th>
<th>
<input type="password" value="" id="password" name="password" />
</th>
</tr>
<tr>
<th></th>
<th>
<input type="submit" value="Login" name="sub" />
</th>
</tr>
</form>
</table>
</center>
</body>
</html>
admin.php: Checks for session "login", if session was set then it will proceed further otherwise it will go to login.php
<?php
session_start();
if (!isset($_SESSION['login']))
{
header('LOCATION:login.php');
die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
<center>
<h1>Succesfully logged in</h1>
<input type="button" value="Logout" onclick='window.open("/logout.php","_self")'/>
</center>
</body>
</html>
logout.php: Clears the session, cookies and close them and returns to login.php
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name() , '', 0, '/');
session_regenerate_id(true);
header("Location: /index.php");
die();
?>
put them in same folder it will work.

PHP $_SESSION Not checking login status

I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.

PHP - Maintain Session Array Between Pages

I have a session variable that's an array and is supposed to store different usernames. Upon a user trying to log in, the username is checked against the array to see if the name exists within the array. If it's not found within the array the user is re-directed to a registration page, where the user can enter in a username and password.
This page, upon accepting the username and password, is supposed to update the session array, so that the next time the user tries logging in he/she is redirected to a different page.
I am able to register, but think that each time I go back to my main page the usernames array is refreshed to contain 0 entries.
Any way I can make my array more persistent?
products.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Studen Project #6 - M.M.</title>
<link rel="stylesheet" href="mystyles.css" />
</head>
<body>
<h1>Product Listings</h1>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username: <input type="text" name="username" /><br>
Password: <input type="password" name="password" /><br><br>
Enter a Quantity for Each Product<br><br>
Pencils: <input type="number" name="pencils" /><br>
Notebooks: <input type="number" name="notebooks" /><br>
Folders: <input type="number" name="folders" /><br><br>
<input type="submit" />
</form>
<h2>Dixon Ticonderoga Wood-Cased Pencils</h2>
<h3>$2.88</h3>
<img src="http://ecx.images-amazon.com/images/I/41OAcvBFqXL.jpg" alt="pencil" />
<p>The World's Best Pencil with an exclusive #2 HB graphite core formula provides extra smooth performance</p>
<h2>Five Star Stay-Put Pocket Folder</h2>
<h3>$5.49</h3>
<img src="http://ecx.images-amazon.com/images/I/71HaaqlhilL._SL1280_.jpg" alt="folder" />
<p>Durable plastic folder helps keep sheets protected and in one place; great for reports, projects, as a take-home folder and for storage</p>
<h2>Five Star Wirebound Notebook</h2>
<h3>$18.98</h3>
<img src="http://ecx.images-amazon.com/images/I/61NgdQwSjIL._SL1000_.jpg" alt="notebook" />
<p>Five-subject plastic cover notebook has 200 college-ruled, 11 x 8.5 inch, 3-hole punched sheets</p>
<?php
$usernames = array();
$_SESSION["usernames"];
$_SESSION["quantity_total"];
$_SESSION["username"];
$_SESSION["pencils"];
$_SESSION["folders"];
$_SESSION["notebooks"];
if($_SERVER["REQUEST_METHOD"] === "POST") {
$_SESSION["usernames"] = $usernames;
$_SESSION["username"] = $_POST["username"];
$_SESSION["pencils"] = $_POST["pencils"];
$_SESSION["folders"] = $_POST["folders"];
$_SESSION["notebooks"] = $_POST["notebooks"];
if(!in_array($_SESSION["username"], $_SESSION["usernames"])) {
header("Location:registration.php");
exit();
} else {
$_SESSION["quantity_total"] = $_SESSION["pencils"] * 2.88 +
$_SESSION["folders"] * 5.49 + $_SESSION["notebooks"] * 18.98;
header("Location:preview.php");
exit();
}
}
?>
</body>
</html>
registration.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Student Project #6 - M.M.</title>
<style>
body {
background-color: lightgreen;
margin: auto;
width: 75%;
text-align: center;
}
h1 {
color: blue;
text-decoration: underline;
}
img {
width: 100px;
height: 100px;
}
form {
padding: 5px;
background-color: lightblue;
font-weight: bold;
font-family: Arial;
}
</style>
</head>
<body>
<h1>Register Here!</h1>
<img src="http://0.media.dorkly.cvcdn.com/36/35/6603dc5a9292104b44c349b85b5aaf7a-5-crazy-fan-theories-that-make-total-sense.jpg"
alt="thumbsup"><br>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" />
</form>
<?php
if($_SERVER["REQUEST_METHOD"] === "POST") {
array_push($_SESSION["usernames"], $_POST["username"]);
header("Location: products.php");
}
?>
</body>
</html>
You might consider rethinking the logic behind storing the list of users/usernames and their properties in the session.
With time, sessions will get bigger and bigger and you're going to have more problems down the line.
Instead, store that information in a database and consult it when needed.
Relative to your issue, the problem you're having with the session array being reset after the data is submitted is caused by this:
#line 41 $usernames = array(); <--- variable set to an empty array
...
if($_SERVER["REQUEST_METHOD"] === "POST") {
#line 50 $_SESSION["usernames"] = $usernames; <---- session variable affected with an empty array
$_SESSION["username"] = $_POST["username"];
...
Hope it helps. Good luck

PHP Password Protect page - redirect

I am using the PHP password protection snippet from http://www.fullypixel.com/page/tutorials.html/_/fully-pixel-forum-faq/simple-php-password-protection-for-a-single-page-r27 which looks like....
<?php
if (!isset($_POST['txtAccCode']))
{
//If not isset -> set with dummy value
$_POST['txtAccCode'] = "undefine";
}
// Define your user array
$access_codeArray = array("john","paul","george","ringo","b4dh39gsv55x");
$access_code = $_POST['txtAccCode'];
$result = in_array($access_code, $access_codeArray);
if ($_POST['txtAccCode'] != $result) {
?>
<style type="text/css">
#login {margin:0 auto; width:500px;}
.login {font-family:"Verdana", sans-serif;border:2px solid #3753f5;}
.login p {font-size:13.0px;}
.login p {padding-left:10px;}
h2.login {padding:10px;}
</style>
<div id="login">
<h2 class="login">Enter Access Code to view content</h2>
<form class="login" name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><label for="txtAccCode">Enter Access Code:</label>
<br /><input type="text" title="Enter Access Code" name="txtAccCode" /></p>
<p><input type="submit" name="Submit" value="Login" /></p>
</form>
</div>
<?php
echo '<script> alert ("Please enter a valid access code to continue.");; </script>';
} else { ?>
Everything works great but I am now trying to modify it so that it redirects when the correct password is input rather than display hidden content.
Is this something I should be doing in PHP or will I need to use javascript to do this?
In the end of your example, you have else, so:
// ...
} else {
header('Location: http://google.com');
exit;
}
Once the user fulfills the conditions required to be logged, you should redirect:
if(empty($errors) && $_POST) #not erros, user validated then
{
exit(header('Location: logeed_user_landing.php));
}

Categories