$_SESSION does not keep values between pages [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Observation:
Sending form data from page_1 and page_2 does not show both data in result file.
If sending page_1 one sees the result in result file. When sending page_2 the result of page_1 is gone and you only see the page_2. It behaves as the content of $_SESSION['data'] is
overwritten every time one sends either page_1 or page_2.
The session id of all 3 pages are identical.
Wanted result:
Every time running result.php one should see the accumulated actions, e.g. if pressing page_1 first time you only see page_1 data, if pressing page_2 you would see both page_1- and page_2- data. When pressing page_1 the second time, the page_1 value should be updated and visible when pressing result.php
PHP version
Terminal: PHP 7.4.6
Browser: 7.3.18-1+ubuntu18.04.1+deb.sury.org+1
Page_1:
<?php
session_start();
echo session_id();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page-1</title>
</head>
<body>
<form method="post">
<br><br>
<input type="text" name="input_1" value="">
<button type="submit" name="button">Save</button>
</form>
<pre>
<?php
$_SESSION["data"] = $_POST;
print_r($_SESSION);
?>
</body>
</html>
Page_2:
<?php
session_start();
echo session_id();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page-2</title>
</head>
<body>
<form method="post">
<br><br>
<input type="text" name="input_2" value="">
<button type="submit" name="button">Save</button>
</form>
<pre>
<?php
$_SESSION["data"] = $_POST;
print_r($_SESSION);
?>
</body>
</html>
Result:
<pre>
<?php
session_start();
echo session_id() . "<br /><br />";
print_r($_SESSION);

Every time you send form you overwrite $_SESSION
You should use either
if(!empty($_POST)) {
$_SESSION["data"]['page1'] = $_POST; //and analogically for page2
}
OR
$_SESSION["data"] = array_merge($_SESSION["data"],$_POST);

It behaves as the content of $_SESSION['data'] is overwritten every time one sends either page_1 or page_2.
Because this is exactly what you're doing. The line $_SESSION["data"] = $_POST; appears in both page_1 and page_2, and there's nothing that preserves the old value of $_SESSION["data"] before new data is written.
If you want to add the data instead of replacing it, you could write, for example, $_SESSION["data"][] = $_POST; in both pages. This will create an array in $_SESSION["data"] and append $_POST data to it each time you open either page.

Related

On a loop: fgets keeps reading only one line that keeps getting used in the following loop

My goal from my code (using only HTML and PHP) is to provide a page for choosing the type of question (checkbox...) with the number of inputs and display the result in a different page by reading the 3 files that has been already saved in 3 main files (file for questions, file for number of inputs, file for options content), my idea is almost.
Here's my code from the displaying page :
<!doctype html>
<html>
<head>
<title>
form du reponse
</title>
</head>
<body>
<?php
//3 files
$k=fopen("choix multiples.txt","a+");//questions
$nn=fopen("nombre.txt","a+");//number of inputs
$no=fopen("les_options_multiples.txt","a+");//options content
//from here it only reads the first line of $nn and it keeps using it on the last loop
for($lol=fgets($nn);!feof($nn);$lol=fgets($nn))
{
for($questioncm=fgets($k);!feof($k);$questioncm=fgets($k))
{
echo "$questioncm :<br/>";
for($x=1;$x<=$lol;$x++)
{
echo fgets($no);
?>
<form action="" method="POST">
<div>
<input name="haha" type="radio" value="hahaha">
</div>
<?php
}
?>
</form>
<?php
}
}
</form>
</body>
</html>

PHP - $_SESSION does not retain data after page refresh

I have the following problem and feel that the solution is simple but after 8 hours of trying and searching, I am giving up.
I have this simple page:
<?php
// Start the session
$lifetime=600;
session_set_cookie_params($lifetime);
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Change the Yoda!</title>
</head>
<body>
<?php
// Set session variables
$_SESSION["post-data"] = $_POST;
?>
<form action="yoda_is.php" method="POST">
YODA IS: <input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
Upon submit, it sends me to this page:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Who is Yoda?</title>
</head>
<body>
<?php
// Echo session variables that were set on previous page
echo "YODA IS " . $_SESSION['post-data'] = $_POST['name'];
?>!
</body>
</html>
The value that you enter in the first page, is successfully being displayed on the second page.
However, once I close the browser window and revisit the second page, the value is no longer there and it returns an error.
My question is simple, what am I doing wrong / do I need to do in order for the value that I entered on the first page, to be there after I revisit the second page?
Thank you so much for your help and suggestions, in advanced.
KR
MD
On your first page remove this:
// Set session variables
$_SESSION["post-data"] = $_POST;
On your second page use this instead:
// If the user filled out the form, set our session variable to the new value
if(isset($_POST['name']))
{
$_SESSION['post-data'] = $_POST['name'];
}
// Echo session variable set above
echo "YODA IS " . $_SESSION['post-data'] . "!";

PHP Wamp server [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Hey I have a database that contains information about different countries. I also have a html page where you can submit information about countries. Can someone help me to write a code that says that the information has been stored in the database instead of it just redirecting to a blank page?
Here is my html page where you submit information:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Sett inn land</title>
</head>
<body>
<form action="geoinn.php" method="get">
Land: <input type="text" name="navn"> <br>
Hovedstad: <input type="text" name="hovedstad"> <br>
Areal: <input type="text" name="areal"> <br>
Folketall: <input type="text" name="folketall"> <br>
<input type="submit" value="Legg inn informasjon">
</form>
</body>
</html>
And here is the page that you are redirected to when you click submit on the other page. This is the page where I want to have a code saying either that "The information has been stored in our database" or that it has not:
<?php
$tjener = "localhost";
$brukernavn = "root";
$passord ="";
$database ="Geografi";
$kobling = mysqli_connect($tjener,$brukernavn,$passord,$database);
$kobling->set_charset("utf8");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Geografi</title>
</head>
<body>
<?php
$land = $_GET["navn"];
$hovedstad = $_GET["hovedstad"];
$areal = $_GET["areal"];
$folketall = $_GET["folketall"];
$sql ="INSERT INTO land (navn,hovedstad, areal, folketall) VALUES('$land','$hovedstad','$areal', '$folketall')";
mysqli_query($kobling, $sql);
mysqli_close($kobling);
?>
</body>
</html>
Add some output and you will get some output. The blank page you get is the page that does the updates. You add the basic HTML page tags but do not output anything inside the <body>
$sql ="INSERT INTO land
(navn,hovedstad, areal, folketall)
VALUES('$land','$hovedstad','$areal', '$folketall')";
$result = mysqli_query($kobling, $sql);
if ( $result === FALSE ) {
echo '<p>FAILED MESSAGE</p>';
} else {
echo '<p>SUCCESS MESSAGE</p>';
}
echo "<p>Land = $land</p>";
echo "<p>hovedstad = $hovedstad</p>";
// and so on
mysqli_close($kobling);
As Jay says,
Your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi.

Using multiple PHP files while avoiding redirect loop and resubmission

So I am pretty new to PHP, I have done and learnt lots of console based experience so I'm not a full beginner to programming. But I decided to learn how to database because its always fascinated me, and I've learnt the basic HTML and CSS and JS, and now basic PHP and SQL, but putting into action is getting weird on me.
I've figured out how to manipulate and make databases through PHP code and stuff like that, but they were all simple things and in one file, I am going for a bigger project and I need to put all the PHP's in separate files, this is the problem.
say my 'index.php' file is so:
<!DOCTYPE html>
<html>
<head>
<?php include 'other.php' ?> //Problem 1
</head>
<body>
<FORM method="POST" action="other.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
and my 'other.php' is :
<?php
$input = "";
if (isset ($_POST['subTest']))
{
$input = $_POST['textTest'];
//header("Location : index.php");
}
header("Location: index.php"); //Problem 2
?>
so my problems:
Problem 1, if I don't include the 'other.php' file, there is an error when I try print the: value = "print $input"
Problem 2, if I don't redirect with 'header', it obviously doesn't redirect and go back to the 'index.php' which I want to happen. BUT with it there, it causes a TOO_MANY_REDIRECT error. I found this is a problem caused by the include which can't be removed for Problem 1 reasons.
Problem 3, I found out I could move the 'header' function to where it is commented out, but then the value="..." doesn't stay on submit.
Problem 4, if I completely get rid of the 'header' redirect, and change the form's action to 'index.php', then I get the 'Confirm Form Resubmission' thing I want to avoid.
So I hope that is a mouthful someone understands and can help with, and thankyou in advanced.
include does what it sounds like, it includes the file into the parent, essentially the same as copy and pasting the content into it.
So to fix your problem, 1st change the forms action to index.php (so it posts to its self), and remove the redirect all together:
<?php include 'other.php' ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<FORM method="POST" action="index.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
other.php:
<?php
$input = "";
if (isset ($_POST['subTest'])){
$input = $_POST['textTest'];
}
Note that i also moved the include to the 1st line in index.php, before any html output.
This is not strictly required in this instance, but is a good practice, as you are unable to set headers (eg for a redirect) after the response body is sent to the output stream
EDIT
If you want to avoid form resubmits on refresh, then you are correct that you would need to submit to a seperate endpoint and redirect.
To do that you would need to pass the posted data back to the index file, as the redirect is a new (GET) request, so the post data is lost.
The two main ways to do that would be with SESSION or URL parameters.
I'll show how to do it with parameters:
Dont include the destination file:
<?php
//get value from url parameter, or set to empty string if parameter not present
$input = isset($_GET['input'])? $_GET['input'] : '';
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<FORM method="POST" action="other.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
Then append the required data to the redirect url as parameters
other.php:
<?php
$input = "";
if (isset ($_POST['subTest'])){
$input = $_POST['textTest'];
header("Location: index.php?" . http_build_query(['input'=>$input]));
die(); //always stop execution after redirect
}
//if post data not sent, something went wrong, so set $input parameter to error message
header("Location: index.php?" . http_build_query(['input'=>'No Data posted']));
die(); //always stop execution after redirect
In other.php at the last line try require-ing the index.php instead of redirrecting.
Also remove the inclusion of other.php in index.php .
$input = "";
if (isset ($_POST['subTest']))
{
$input = $_POST['textTest'];
}
require_once 'index.php';
?>

Does action attribute in html forms interfere with what's stored in $_SESSION global variable?

Suppose, I have two pages: page01.php and page02.php (their code is presented below).
If I leave action attribute in the form on page01.php empty (i.e. action=""), then access page01.php, fill in the form, press submit, then access page02.php - it all works fine (i.e. $_SESSION variable stores the data submitted on page01.php and can be accessed and viewed on page02.php as expected).
However, when I try to make the form send the user to page02.php (by changing the action atrribute to action="page02.php") it looks like the $_SESSION global variable doesn't store data from page01.php.
My question is: does this happen because the user is redirected to page02.php immediately upon submission of form and the code between php tags on page01.php does not get executed?
I'm aware I can use $_GET or $_POST on page02.php to achieve the desired behavior, but I'm just trying to understand the way action attribute and $_SESSION interact. Thank you.
Page01.php:
<html>
<head>
<title>Page 01</title>
</head>
<body>
<h1>Please fill this form</h1>
<form action="" method="post">
Name: <input name="username">
<input type="submit" value="send">
</form>
<?php
session_start();
if(isset($_POST['username'])) {
$_SESSION['username']=$_POST['username'];
}
?>
</body>
Page02.php:
<html>
<head>
<title>Page 02</title>
</head>
<body>
<h1>Another temporary page is working</h1>
<?php
session_start();
$expectedName = "Bob";
if($_SESSION['username'] == $expectedName) {
echo "Welcome, Bob!";
}
else {
echo "Access denied. You are ". $_SESSION['username'] . ", not Bob.";
}
?>
</body>
action attribute is attribute you specify where the script that will need to be run after submitting.
so if you want user to be redirected after form has been submitted, you use header() function.

Categories