Form will not add text input to session [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed last year.
I am trying to add data from a form on one page and send it to another. I have done this elsewhere on the first page and it adds the data. I try it again and when I echo it out on the second page I get a null value.
Session was already started at the top of the page.
Code on the first page:
<?php
if(!isset($_POST['submit'])){}
else{
$var_fname = $_SESSION['fname'] = $_POST['fname'];
$var_lname = $_SESSION['lname'] = $_POST['lname'];
$var_address = $_SESSION['address'] = $_POST['address'];
$var_city = $_SESSION['city'] = $_POST['city'];
$var_state = $_SESSION['state'] = $_POST['state'];
$var_zip = $_SESSION['zip'] = $_POST['zip'];
$var_email = $_SESSION['email'] = $_POST['email'];
};
?>
Code on the second page:
<?php
/**
* #author
* #copyright 2022
*/
session_start();
echo $var_session = json_encode($_SESSION["shopping_cart"]);
?>
<html>
<body>
<br /><br /><br />
</body>
</html>
<?php
//echo $var_email = json_encode($_SESSION["email"]);
echo $var_fname = json_encode($_SESSION["fname"]);
?>**
The second echo outputs NULL.
Form I used to gather the data:
<form method="post" action='email.php'>
First name: <input type="text" name="fname"/><br />
Last name: <input type="text" name="lname"/><br />
Address: <input type="text" name="address"/><br />
City: <input type="text" name="city"/><br />
State: <input type="text" name="state" /><br />
Zip code: <input type="text" name="zip"/><br />
Email: <input type="text" name="email"/><br />
<button type="submit">Continue to checkout</button>
</form>
--output on second page:
{"Bag01":{"name":"Laptop Bag","code":"Bag01","price":"50.00","quantity":1,"image":"product-images\/laptop-bag.jpg"}}
shopping_cart|a:1:{s:5:"Bag01";a:5:{s:4:"name";s:10:"Laptop Bag";s:4:"code";s:5:"Bag01";s:5:"price";s:5:"50.00";s:8:"quantity";i:1;s:5:"image";s:29:"product-images/laptop-bag.jpg";}}

Change -> if(!isset($_POST['submit'])){}
to isset , because you want to post it if the submit button is set right?
i would change this:
$var_fname = $_SESSION['fname'] = $_POST['fname'];
$var_lname = $_SESSION['lname'] = $_POST['lname'];
.....
to something like this
$var_firstname = $_POST['fname'];
$_SESSION['fname'] = $var_firstname;
and so on

Related

Session not taking text from form

I have not found an answer anywhere else.
Still having a problem adding form textbox values to the session. The code as it stands won't even add to the session from this particular form. It had before until I closed the browser to restart the session. When it was sending the session correctly to the second page the values for fname, lname, address ect was fname:|N which I am assuming in a null value? Every page the sesson_start(); is called at the top.
Code for the form:
<form method='post' action='email.php'>
First name: <input type="text" name="fname"/><br />
Last name: <input type="text" name="lname"/><br />
Address: <input type="text" name="address"/><br />
City: <input type="text" name="city"/><br />
State: <input type="text" name="state" /><br />
Zip code: <input type="text" name="zip"/><br />
Email: <input type="text" name="email"/><br />
<button type="submit" name="submit">Continue to checkout</button>
</form>
<?php
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//$_SESSION['fname'] = $var_fname;
$_SESSION['lname'] = $_POST['lname'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['city'] = $_POST['city'];
$_SESSION['state'] = $_POST['state'];
$_SESSION['zip'] = $_POST['zip'];
$_SESSION['email'] = $_POST['email'];
}
?>
Code on second page echo'ing the session:
<?php
session_start();
echo $var_session = json_encode($_SESSION["shopping_cart"]);
?>
<html>
<body>
<br /><br /><br />
<?php
echo session_encode();
//echo $var_email = json_encode($_SESSION["email"]);
//echo $var_fname = json_encode($_SESSION["fname"]);
//echo $var_email = $_SESSION["email"];
?>
</body>
</html>

How to fix no variable echoed in PHP Post request?

I am setting up a new website and want to be able to gather user input on the checkout page and echo the user input on the confirmation page. How do I perform this operation?
This is using html and php. In the past, I've tried using POST method, isset, $_Request functions.
This is the code for Confirmationpage.html.
<!DOCTYPE html>
<html>
<head>
<title>Confirmation page</title>
</head>
<body>
<h1>Confirmation page</h1>
<h2>Order Confirmed!</h2>
<?php
// define variables and set to empty values
$fName = $lName = $email = $phoneNumber = "";
if ( isset( $_POST['submit'] ) ) {
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$email = $_POST["email"];
$phoneNumber = $_POST["phoneNumber"];
echo $fName . " " . $lName;
echo $email;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
This is the code for Checkoutpage.html.
<!DOCTYPE html>
<html>
<head>
<title>Checkout page</title>
</head>
<body>
<h1>Checkout page</h1>
<form action="Confirmationpage.html" method="POST">
<input type="text" name="fName" placeholder="First Name"><br>
<input type="text" name="lName" placeholder="Last Name"><br>
<input type="email" name="email" placeholder="Email"><br>
<input type="number" name="phoneNumber" placeholder="Phone Number">
<br>
<input type="submit" value="Confirm" name="submit">
</form>
</body>
</html>
I expected the first name, last name and email to be echoed in the confirmation page however the actual result is not outputting the first name, last name and email.
try this,
echo $fName . " " . $lName;
echo '<br>';
echo $email;die;
Keep this in mind: your file should be .php

I can't insert data into my database while in a Session

I have the tables users and register in my database. I've created a login page which starts a session using the users table, then people fill out a form to insert data into the register table. I've used the following code to insert the data. My code doesn't have errors but the thing is it is not inserted to my table. Please help me. Thanks.
<?php
include("includes/db.php");
session_start();
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else { ?>
<html>
<body>
<h2>New users Signup!</h2>
<form action="login.php" method="post">
<input type="text" name = "firstname" placeholder="Firstname"/>
<input type="text" name = "lastname" placeholder="Lastname"/>
<input type="text" name = "address" placeholder="Address"/>
<input type="text" name = "contact" placeholder="Contact"/>
<input type="text" name = "email" placeholder="Email Address"/>
<input type="password" name = "password" placeholder="Password"/>
<div class = "bttn">
<button type="submit" name = "submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
} else {
$insert_query = mysql_query("insert into users (users_firstname,users_lastname,users_address,users_contact,users_email,users_password,users_date) values ('$users_firstname','$users_lastname','$users_address','$users_contact','$users_email','$users_password','$users_date')");
$users_id=mysql_insert_id();
if(mysql_query($insert_query)) {
echo "<script>alert('post published successfuly')</script>";
}
}
}
} ?>
Now try this code:
<?php
include("includes/db.php");
session_start();
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else {
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
}
else
{
$insert_query = mysql_query("INSERT INTO `users` (users_firstname, users_lastname, users_address, users_contact, users_email, users_password, users_date) values ('$users_firstname', '$users_lastname', '$users_address', '$users_contact', '$users_email', '$users_password', '$users_date')");
$users_id=mysql_insert_id();
echo "<script>alert('post published successfuly')</script>";
}
}
?>
<h2>New users Signup!</h2>
<form action="" method="post">
<input type="text" name="firstname" placeholder="Firstname"/>
<input type="text" name="lastname" placeholder="Lastname"/>
<input type="text" name="address" placeholder="Address"/>
<input type="text" name="contact" placeholder="Contact"/>
<input type="text" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password"/>
<div class="bttn">
<button type="submit" name="submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php } ?>
I have:
Repositioned your PHP code for inserting to be at the top of the form
changed <form action="login.php" to <form action="" because we are executing from the same page
Your query has already run so removed the if(mysql_query...
Removed the spaces in the form e.g. name = " nameofform" to name="nameofform"
I don't see any reason for having this $users_id=mysql_insert_id();, YOu should use auto-increment for the userID on your database
But since we don't know how you have connected to your database, because also that can be an issue: you can also try this way
<?php
//connect to DB
$hostname_localhost = "localhost"; //hostname if it is not localhost
$database_localhost = "databasename";
$username_localhost = "root"; //the username if it is not root
$password_localhost = "password_if_any"; //if no password leave empty
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
// include("includes/db.php");
if (!isset($_SESSION)) {
session_start();
}
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else {
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
}
else
{
$insert_query = sprintf("INSERT INTO `users` (users_firstname, users_lastname, users_address, users_contact, users_email, users_password, users_date) values ('$users_firstname', '$users_lastname', '$users_address', '$users_contact', '$users_email', '$users_password', '$users_date')");
mysql_select_db($database_localhost, $localhost);
$Result = mysql_query($insert_query, $localhost) or die(mysql_error());
echo "<script>alert('post published successfuly')</script>";
}
}
?>
<h2>New users Signup!</h2>
<form action="" method="post">
<input type="text" name="firstname" placeholder="Firstname"/>
<input type="text" name="lastname" placeholder="Lastname"/>
<input type="text" name="address" placeholder="Address"/>
<input type="text" name="contact" placeholder="Contact"/>
<input type="text" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password"/>
<div class = "bttn">
<button type="submit" name="submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php } ?>
You should removed the whitespaces in your html-code:
Wrong
<input type="text" name = "firstname" placeholder="Firstname"/>
^^^^^
Correct
<input type="text" name="firstname" placeholder="Firstname"/>
Do not put the variables in single quotes:
$insert_query = mysql_query("INSERT INTO users
(users_firstname,users_lastname,users_address,users_contact,users_email,users_password,users_date)
VALUES
($users_firstname,$users_lastname,$users_address,$users_contact,$users_email,$users_password,$users_date)");
Update: This was wrong. The whole string is in double-quotes so the OP did correct and my notice was wrong. For information-purposes i will let stand the link to the documentation here.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Read more about single- and double-quotes in the PHP documentation.
Do not double-run the query/perform wrong function-call
$insert_query = mysql_query(".......");
........
if(mysql_query($insert_query)){
echo "<script>alert('post published successfuly')</script>";
}
You already have run the query in the first line. If you want to check if it was successful, you have to use if($insert_query) {}. The call mysql_query($insert_query) is wrong because mysql_query() returns a ressource instead of the sql-query.
Do not use mysql_*() function calls. You mysqli_*() instead.
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
Check your use of session.
You are checking the $_SESSION for user_name and if it is not set, you are redirecting via header("location: login.php").
The problem is, that you are never inserting the user_name into the session, so it will always be not set.
You can set the value via $_SESSION['user_name'] = $_POST['user_name']. Have in mind that you have to set the session before checking the session-value. ;-)
remove action
Try this
<form action="" method="post">

pass post value from one php to another php page

I have 2 php scripts one that takes the values from a form on an html page and just return them to the user so he can check they are correct i then want to allow him to confirm then by pressing a submit button, the values will then be written on a txt file.
Here is my code that i have so far, the script return that the values are being written on the file but there is nothing in the file>
code:
fist php:
$surname = $_POST['surname'];
$lastname = $_POST['lastname'];
$mail = $_POST['mail'];
<div id="oneConatiner">
<h1>Please confirm the details of your order:</h1>
<div align="left" id='php'>
<form name="info" method="post" action="confirmation.php">
<p>Your surname is: <?php echo $surname . "<p>"; ?>
<p>Your lastname is: <?php echo $lastname . "</p></div>"; ?>
<p>Your email is: <?php echo $mail . "<p>"; ?>
<p><input type="submit" name="Submit" value="Confirm" /></p>
</form>
</div>
Second php:
<?php
$surname = $_POST['surname'];
$lastname = $_POST['lastname'];
$mail = $_POST['mail'];
$page = ceil($quantity / 10);
$data = "$surname,$lastname,$mail\r\n";
$fh = fopen("user.txt", "a");
fwrite($fh, $data);
fclose($fh);
if (fwrite == FALSE){
echo "fail";
} else {
echo "successful";
}
?>
The values you want to submit need to be form inputs of some kind. I'll use text fields for this example:
<form name="info" method="post" action="confirmation.php">
<p>Your surname is: <input name="surname" value="<?php echo htmlentities($surname); ?>"></p>
<p>Your lastname is: <input name="lastname" value="<?php echo htmlentities($lastname); ?>"></p>
<p>Your email is: <input name="mail" value="<?php echo htmlentities($mail); ?>"></p>
<p><input type="submit" name="Submit" value="Confirm" /></p>
</form>
If you don't want these fields to be editable, you can either set the fields to readonly or use hidden inputs instead.
The only error that I see and needs to be corrected is that the word fwrite in the if-conditional should be changed to $fh otherwise the code works. It worked for me.
Make sure the $surname, $lastname and $mail are not empty and you have read and write permissions for the folder where user.txt is supposed to be stored.

how to allow users logged in to UPDATE / EDIT their profile settings/information

Question at hand:
How do I create the php code to let users who are logged into my site edit/update their profile settings/information?
I have 1 part working correctly for users to change their password, however, have no idea where to start when it comes to allowing users who are logged in to edit/update their other settings such as:
(1) nickname,
(2) country,
(3) date of birth,
(4) gender,
(5) motto and
(6) bio
I'll provide the php and html code below that I have that is working for changing password, but I know that I need more to let users change/edit/update their other information. I tried using what is below as a reference to create the php code for the other information, but it didn't work so I have no idea where to even begin! Any help will be much appreciated...
PHP reference code:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] = mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM members WHERE username='{$_SESSION['username']}' AND pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = "UPDATE members SET pass='".md5($_POST['passwordnew1'])."' WHERE username='{$_SESSION['username']}'";
$result = mysql_query($querynewpass) or die(mysql_error());
$_SESSION['msg']['passwordchange-success']='* You have successfully changed your password!';
}
else $err[]='Wrong password to start with!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML reference code:
<form action="" method="post">
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1" value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1" id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register" style="margin-left: 382px;" />
<div class="clear"></div>
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
</form>
So how would I create the php code to make this work for users to be able to edit/update their own profile settings/information from the numeric list I provided above (1-6)?
And I know using mysqli/pdo is a better alternative to use, but I unfortunately need to use the old deprecated mysql_* stuff for this project at this time...
If you need more info, let me know ;)
EDIT:
Additional Question,
I'd assume too that I'd need to create variables for each column too such as:
$nickname = $_POST['nickname'];
$country = $_POST['country'];
etc...or is that not correct?
RE-EDIT:
Would something like this be applicable?
$id = $_SESSION['id'];
if ($_POST['country']) {
$country = $_POST['country'];
$nickname = $_POST['nickname'];
$DOB = $_POST['DOB'];
$gender = $_POST['gender'];
$motto = $_POST['motto'];
$bio = $_POST['bio'];
$sql = mysql_query("UPDATE members SET country='$country', nickname='$nickname', DOB='$DOB', gender='$gender', motto='$motto', bio='$bio' WHERE id='$id'");
exit;
}
$sql = mysql_query("SELECT * FROM members WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
$country = $row["country"];
$nickname = $row["nickname"];
$DOB = $row["DOB"];
$gender = $row["gender"];
$motto = $row["motto"];
$bio = $row["bio"];
}
Or am I way off base?
short version ;)
HTML file:
<form action="./change.php" method="post">
Nickname: <input type="text" name="nickname"><br />
Country: <input type="text" name="country"><br />
Date of birth: <input type="text" name="date_of_birth"><br />
Gender: <input type="text" name="gender"><br />
Motto: <input type="text" name="motto"><br />
Bio: <input type="text" name="bio"><br />
<input type="submit" value="Submit">
</form>
change.php:
<?php
function filter($date)
{
return trim(htmlspecialchars($date));
}
$nickname = filter($_POST['nickname'])
$country = filter($_POST['country'])
$date_of_birth = filter($_POST['date_of_birth'])
$gender = filter($_POST['gender'])
$motto = filter($_POST['motto'])
$bio = filter($_POST['bio'])
if (isUserLogIn)
{
//SQL update query
}
?>

Categories