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

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;
}

Related

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.

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

How to get value from php to html tag?

My first HTML file has a form a with a radio button. I want the second file (which is PHP) to print a message about what they choose. With that message thought, I would like to have some text formating (size, color, etc.).
file.html:
<html>
<body>
<form action="file.php" method="post">
<input type="radio" name="favorite" value="rbOne">
<input type="radio" name="favorite" value="rbTwo">
<input type="submit" value="Submit">
</form>
</body>
</html>
file.php:
<html>
<head>
<style>
body{
background-color:white;
}
p{
color:white;
font-size:50px;
font-weight:bold;
}
</style>
</head>
<body>
<?php $choice = $POST_['favorite']; ?>
<p align="center">Thanks for voting for <?php echo "$choice" ?>!!</p>
</body>
</html>
When I click the Submit button, it going to the file.php page, but it displays this:
Thanks for voting for !!
It makes $choice blank.
You need PHP opening and closing tags:
<?php echo $choice;?>
Also, $POST_['favorite'] should be $_POST['favorite']

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"]){

Why i get everytime the error-message that i've already sent the headers

i've another question about web-programming.
I programmed a login script, but everytime when i try to login it says that i've send the header informations already.
Here are the 2 files:
<?php
if($_GET['logout'] == 1) {
setcookie('authorized', 1, time()-3600);
}
?>
<!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>
<title>Login - photoAdminSite</title>
</head>
<style type="text/css">
body {
text-align: center;
font-family: helvetica;
}
#loginForm {
padding: 1em;
background: #e3e3e3;
width: 260px;
margin: 3em auto 0;
text-align: left;
}
</style>
<body>
<div id="loginForm">
<form method="post" action="confirm_login_credentials.php">
<h2>LOGIN</h2>
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="password" name="password" /></p>
<p><input type="submit" value="Login" name="submit" /></p>
</form>
</div>
</body>
</html>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
require 'database.php';
$q = "SELECT id FROM users_photoadminsite WHERE user_name = '$username' AND password = '$password'";
$result = $mysqli->query($q) or die(mysqli_error());
if (mysqli_num_rows($result) == 1) {
setcookie('authorized', 1, 0);
header("Location: index.php");
} else {
header("Location: login.php");
}
?>
i would be really happy about some helpful answers.
Cookies and Headers must be set before any output is sent to the browser. Try moving your login script to the top of the page. You might want to also consider sanitizing your queries to prevent malicious activity.
You might have an empty line in the beginning of that php file. Maybe space before start of PHP script
See lines 60, 61, and 63, and how they come after all your HTML? Put them before instead.
When PHP says it's already sent the headers, it means that some text has already been output by the script (or the script that called it). This includes any and all error messages.
When the FIRST piece of text is output by PHP it sends its headers, but not before. In order to get HTTP cookies (part of the headers) to be set, the cookies must be sent before any text is output.
What you can do is enable output buffering using ob_start, and ob_end_flush, and other output-control functions.
What you can also do is to set the php.ini variable to automatically send the cookie header when it outputs text.
If you do not have output_buffering enabled in your php.ini you will get this error because it will start sending the html right away. You need to edit your php.ini to enable output buffering.
Is this on Windows? Check for BOM. Open it in Notepad and save it as ANSI to see if it helps.

Categories