PHP - Maintain Session Array Between Pages - php

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

Related

data in $_POST across multiple pages

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>

Simple form wont post to mysql

Simply lost... I have been looking online for the answer but I cannot see why my code won't post to the MySQL database I have on the WAMP server is have installed locally?
also it doesn't echo the results when I'm trying to test if it is getting anything from the form.
here is my code its a simple form using php to insert it into the database.
the database table has ID (Auto Increment), Fname, Lname, Barcode.
<!DOCTYPE html>
<HTML>
<HEAD>
<meta charset="UTF-8">
<TITLE>Testing Barcode Reader</TITLE>
<style type="text/css">
#body {margin: 0px; }
#pageTop {
height: 90px;
background: grey;
padding: 10px;
}
#pageMiddle {
padding: 20px;
height: 250px;
}
#pageBottom {
padding: 20px;
height: 90px;
}
</style>
<?php
if (isset($_POST['submit'])){
$f = $_POST['fname'];
$l = $_POST['Lname'];
$b = $_POST['barcode'];
$db_conx = mysqli_connect('localhost', 'root', 'password');
mysqli_select_db($db_conx,'barcode_test');
$sql = "INSERT INTO barcode (Fname, Lname, Barcode) VALUES ('$f','$l','$b')";
$query = mysqli_query($db_conx, $sql);
}
?>
</HEAD>
<BODY>
<div id="pageTop">
<h1>Testing Barcode Reader</h1>
</div>
<div id="pageMiddle">
<div>
<form action="form.php" method="post">
<div>First Name:</div>
<input name="fname" type="text" /></br></br>
<div>Last Name:</div>
<input name="Lname" type="text" /></br></br>
<div>Barcode:</div>
<input name="barcode" type="text" /></br></br>
<div>Submit Button:</div>
<input name="submit" type="submit" value="Submit"/>
</form>
</div>
</div>
<div id="pageBottom">form for testing barcode reader inputs into mysql database</div>
<?php echo($f);
?>
</BODY>
</HTML>
thanks for any advice you can offer because I'm beginning to believe there is a problem with my WAMP server setup, because even if I copy and paste a simple form from the internet with the database connection settings setup it still wont post or echo?
Is php even working on your server? The best way to test this is by making a file with this code and this code only in it:
<?php phpinfo(); ?>
If the above doesn't work php isn't working correctly on your server.
Also check if you are going to the site by using localhost/filename.php or something similar.

How to transfer input data in php using session [duplicate]

This question already has answers here:
How to store a variable in php using session
(3 answers)
Closed 5 years ago.
I working on the project and I need help with displaying what user typed in input on one page and display on the other page using session.
This is my code for page where user types his/her name:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="s2q2.php" name="s2n" method="POST">
<p>Enter your name:</p>
<input style="border: none; border-bottom: dashed; height: 50px; width:25%; margin-top: 45px; font-size: 35px;" type="text" script="sessionStorage.setItem('s2n');"><br>
<button class="button" type="submit" style="vertical-align: center; background-color: #1e00ff; margin-top: 50px;" name="s2q1"><span>Next </span></button>
</form>
</body>
</html>
First you create a session file called session_start.php that looks like this
<?php
session_start();
?>
then you just need to include it everywhere you want to have your session variables
<!DOCTYPE html>
<html>
<head>
<title>Input Site</title>
<style>
.input1 {
border: none;
border-bottom: dashed;
height: 50px; width:25%;
margin-top: 45px;
font-size: 35px;
}
.button1 {
vertical-align: center;
background-color: #1e00ff;
margin-top: 50px;
}
</style>
</head>
<body>
<form action="" method"post">
<p>Enter your name:</p>
<input class="input1" type="text" name="nameInput"><br>
<button class="button1" type="submit" name="submitBut"><span>Next</span></button>
</form>
<?php
// including the session file
require_once("session_start.php");
if (isset($_POST['submitBut'])) {
$_SESSION['nameInput'] = $_POST['nameInput'];
}
?>
</body>
</html>
then you create whatever site whatever.php and just have include your session_start.php file
<!DOCTYPE html>
<html>
<head>
<title>Whatever Site</title>
</head>
<body>
<?php
// including the session file
require_once("session_start.php");
?>
<strong><?php echo $_SESSION['nameInput'];?></strong>
</body>
</html>
First, modify the form input to have a name :
I working on the project and I need help with displaying what user typed in input on one page and display on the other page using session.
This is my code for page where user types his/her name:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="s2q2.php" name="s2n" method="POST">
<p>Enter your name:</p>
<input name="username" style="border: none; border-bottom: dashed; height: 50px; width:25%; margin-top: 45px; font-size: 35px;" type="text" script="sessionStorage.setItem('s2n');"><br>
<button class="button" type="submit" style="vertical-align: center; background-color: #1e00ff; margin-top: 50px;" name="s2q1"><span>Next </span></button>
</form>
</body>
</html>
then, on s2q2.php page:
<?php
session_start();
$_SESSION["username"] = $_POST["username"];
echo $_SESSION["username"] ;
?>
Oh well, lets see another example ( need to sanitize $name before output! )
<?php
$name = isset($_SESSION['key_whatever']) ? $_SESSION['key_whatever'] :null;
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="s2q2.php" method="POST">
<p>Enter your name:</p>
<input type="text" name="name" value="<?=$name?>">
<br>
<button type="submit" name="s2q1"><span>Next </span></button>
</form>
</body>
</html>
/*
on submit if youre not using any rewrite rules -> s2q2.php will be compiled and executed
-------s2q2.php-------
*/
<?php
session_start(); <--- need to be set
$_SESSION['key_whatever'] = isset($_POST['name']) ? $_POST['name'] : null;
?>
Your question is a bit confusing but from my experience working with PHP here's how we $_POST data and make use of $_SESSION the easy way
EDIT : in your question we don't know whether you know how to use session_start() or not. We also don't know how the files and folders in your program are set up to give proper answer. But usually (well me) I create a config.php file which holds database information then I include that file in the header (header.php) because usually header.php is included everywhere in the program. I created file examples assuming you are using mysqli.
config.php
if (session_status() == PHP_SESSION_NONE) {
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'my_database_name');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
header.php (include this file everywhere you need or else include config.php)
header('Content-Type: text/html; charset=iso-8859-1');
ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);//handle php errors
ob_start();//prevent header from being sent twice
require_once('config.php');
form
require_once('header.php');
<form action="s2q2.php" method="POST">
<p>Enter your name:</p>
<input type="text" name="name"><br>
<button type="submit" name="s2q1"><span>Next </span></button>
</form>
s2q2.php
if (isset($_POST['s2q1'])) { // Retrieve form
$name = $_POST['name']; // retrieve data name
$_SESSION['name'] = $name; // pass data in session
}
Using $_SESSION
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
//do something else;
}

User Session value on fieldset input

I have a code below the submit action, however before this screen, i have a login screen. So with the current
i want to add to the "thisuser" input value below form. Current value is "TEST+USER"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
<title>untitled document</title>
<!--<link rel="stylesheet" href="screen.css" media="screen">-->
<style media="screen">
fieldset {
display: inline-block;
}
input {
display: inline-block;
margin: 0.25em 0;
}
label{
display: inline-block;
width: 7em;
}
</style>
</head>
<body>
<form action="http://trackit/app-copy/curl_create.php" method="get">
<fieldset>
<input type="hidden" name="thisuser" value="TEST+USER">
<label for="summ">Summary:</label>
<input type="text" id="summ" name="summ"><br>
<label for="comment">Description:</label>
<input type="text" id="comment" name="comment"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
You can use
<input type="hidden" name="thisuser" value="<?php echo $_POST['user']; ?>">
Note: It's highly recommended to filter and validate your data to pass it in your code. You may use <?php echo (int)$_POST['user']; ?> to be sure the value is always integer at least.
Note 2: Use POST method instead of GET for your forms.

Invisible CAPTCHA not working, most likely incorrect PHP?

I am trying to incorporate an invisible CAPTCHA into my contact form, however I am not sure if it works.
My code is as follows...
HTML
<span class="test-field"><label for="test">Please leave blank</label>
<input type="text" name="test" id="test"/></span>
CSS
.test-field {Display: none}
PHP
<?php
if($_POST["test"]!=""){
header("Location: {$_SERVER[HTTP_REFERER]}");exit;
}
// Get Data
$f_name = strip_tags($_POST['f_name']);
$f_email = strip_tags($_POST['f_email']);
$f_message = strip_tags($_POST['f_msg']);
// Send Message
mail( "me#website.com", "Website Contact",
"Name: $f_name\nEmail: $f_email\nMessage: $f_message\n",
"From: My Website" );
?>
To test it, I did a few tests changing the...
f($_POST["test"]!="")
...to...
f($_POST["test"]="")
My PHP is not very good, but I am guessing this should not send the form through if the field is blank, but it does come through. Is there anything wrong with my PHP?
Thanks in advance.
As far as your specific question it doesn't make any sense. A user CAPTCHA is absolutely useless if it's hidden.
The term CAPTCHA stands for ...
Completely Automatic Public Turing Test to Tell Computers and Humans Apart
Notice it says humans ...
How can we test for human interaction if they can't see the CAPTCHA challenge? You Can't. Never-the-less .... here's a quick mock up of your code ... the CAPTCHA I left out since it make no sense. Take it from here ...
<?php
if ($_POST['test'] == "") {
header("Location: {$_SERVER['HTTP_REFERER']}");
} else {
// Get Data
$f_name = strip_tags($_POST['f_name']);
$f_email = strip_tags($_POST['f_email']);
$f_message = strip_tags($_POST['f_msg']);
}
?>
<html>
<head>
<style type="text/css">
#demo {
width: 250px;
height: 250px;
}
.test-field {
display: none;
width: 200px;
height: 200px;
}
#form label {
width: 50px;
float: left;
}
#form input {
width: 150px;
float: right;
}
</style>
</head>
<body>
<div id="demo">
<form name="form" id="form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label for="test">Empty </label><input type="text" name="test" id="test"/><br/>
<label for="f_name">Name</label><input type="text" name="f_name" id="f_name"/><br/>
<label for="f_email">Email</label><input type="text" name="f_email" id="f_email"/><br/>
<label for="f_msg">Message</label><textarea rows="15" cols="30" name="f_msg" id="f_msg"></textarea>
<input type="submit" id="submit">
<div class="test-field"></div>
</form>
</div>
</body>
</html>
<?php var_dump($_POST) ?>
Try changing
if($_POST["test"]!=""){
to
if(isset($_POST["test"]) && $_POST["test"]){

Categories