Session not taking text from form - php

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>

Related

Form will not add text input to session [duplicate]

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

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">

Can't insert form data into database (MySQLIi)

EDIT: I'm not sure what to really say. The comments was what helped my issue out right now. I didn't remember the fact to show an error, and that was what helped me. I had pretty much just tried something that obviously wasn't working due to wrongly placed variables and such,and displaying the error code let me know what variables was the faulty ones. Thank you for all your help, and this issue is now resolved!
So long story short, the title. I have no idea why this code refuses to input the inserted data into the database, and I've tried a bunch of things that haven't resulted any better.
Connection:
<?php
session_start();
$host = 'host';
$dbusername = 'username';
$dbpassword = 'password';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('databasename') or die("<b>Could not connect to the specified database</b>");
?>
Form to grab data from :
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
<input type="submit" name="postTopicOnGeneral">
</form>
</div>
';
PHP code to insert it into database
if(isset($_POST['postTopicOnGeneral'])) {
$username = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$general = $_POST['general'];
$addPostOnGeneral = $anslutning->prepare('INSERT INTO tblPosts(title, content, author, category) VALUES(?, ?, ?, ?)');
$addPostOnGeneral->bind_param("ssss", $title, $content, $username, $general);
$addPostOnGeneral->execute();
echo "<center>Post created!</center>";
sleep(2);
echo "<script> window.location.href = 'index.php?general=1' </script>";
}
Undefined index:username and Undefined:general is what I get from that.
You are bound to get that error since you are not fetching $username and $general from anywhere in your form.
Change your form this:
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
<input type="submit" name="postTopicOnGeneral">
</form>
</div>';
to this:
echo '
<h2><center>Post a topic</center></h2>
<br /><br />
<div class="indexform">
<form action="index.php" method="POST">
Title: <input type="text" name="title"> <br /> <br />
Content: <textarea name="content" class="content"> </textarea>
<br /> <br />
Username:
<input type="text" name="username">
General:
<input type="text" name="general">
<input type="submit" name="postTopicOnGeneral">
</form>
</div>';
And then in your index.php:
if(isset($_POST['postTopicOnGeneral'])) {
echo $username = $_POST['username'];
echo $title = $_POST['title'];
echo $content = $_POST['content'];
echo $general = $_POST['general'];
// rest of your code
Try to change
$username = $_POST['username'];
$title = $_POST['title'];
$content = $_POST['content'];
$general = $_POST['general'];
With this:
$username = isset($_POST['username']) ? $_POST['username'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';
$general = isset($_POST['general']) ? $_POST['general'] : '';

How to keep values in register form after error?

My code works perfect with correct data. But when is invalid value in field, it shows an error message with link on page register.php and when I click on this error, it redirects to register form, but there is empty form and all values must be inserted again. I want that valid values are displayed after error and invalid not.
Code:
<html>
<head>
<?php include 'connect.php'; ?>
<?php include 'functions.php'; ?>
<meta charset="UTF-8">
<title>TechnoLab-Registracija</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<?php include 'header.php'; ?>
</head>
<body>
<div id="container">
<div id="left">
<?php include "kategorije.php";?>
</div>
<div id="right">
<?php include "loggedin.php";?>
</div>
<form method="post" id='registerform'>
<br/>
<?php
if(!empty($_POST['username']) && !empty($_POST['password']) )
{
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = md5(mysqli_real_escape_string($con, $_POST['password']));
$email = mysqli_real_escape_string($con, $_POST['email']);
$confirm_email = mysqli_real_escape_string($con, $_POST['confirm_email']);
$ime = mysqli_real_escape_string($con, ucfirst($_POST['ime']));
$prezime = mysqli_real_escape_string($con, ucfirst($_POST['prezime']));
$oib = mysqli_real_escape_string($con, $_POST['oib']);
$ulica = mysqli_real_escape_string($con, $_POST['ulica']);
$mjesto = mysqli_real_escape_string($con, $_POST['mjesto']);
$checkusername = mysqli_query($con, "SELECT * FROM korisnici WHERE Username = '".$username."' OR Oib = '".$oib."'");
if(mysqli_num_rows($checkusername) == 1)
{
echo "&nbsp<p><a class='one' href=\"register.php\">Unesite drugo korisničko ime!</p>";
exit();
}
$checkusernamelenght = checkusernamelenght($username);
if(!$checkusernamelenght){
echo '&nbsp<p><a class="one" href="register.php">Korisničko ime minimalno 4 znaka i ne smije sadržavati razmake između slova!</a></p>';
exit();
}
if (preg_match("/^.*(?=.{6,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST['password']) === 0){
echo '&nbsp<p><a class="one" href="register.php">Lozinka mora imati barem 6 znakova i sadržavati mala i velika slova te broj!</a></p>';
exit();
}
$checkemail = mysqli_query($con, "SELECT * FROM korisnici WHERE Email = '".$email."'");
if(mysqli_num_rows($checkemail) == 1)
{
echo "&nbsp<p><a class='one' href=\"register.php\">Unesite drugu email adresu!</p>";
exit();
}
if ($confirm_email!=$email){
echo "&nbsp<p><a class='one' href=\"register.php\">Vaše email adrese se ne podudaraju!</a></p>" ;
exit();
}
$validateEmail = validateEmail($email);
if(!$validateEmail){
echo "&nbsp<p><a class='one' href=\"register.php\">Unesite ispravan format emaila!</a></p>";
exit();
}
$checkOib = checkOib($oib);
if(!$checkOib){
echo "&nbsp<p><a class='one' href=\"register.php\">Unesite ispravan OIB !</p>";
exit();
}
else{
$registerquery = mysqli_query($con, "INSERT INTO korisnici VALUES('', '$username', '$password', '$email', '$confirm_email', '$ime', '$prezime', '$oib', '$ulica', '$mjesto', 'user')");
if($registerquery)
{
header('location: index');
}
}
}
else
{
?>
<br/>
<div id="reg">
<label for="username">Korisničko ime:</label><input type="text" name="username" required /><br />
<label for="password">Lozinka:</label><input type="password" name="password" maxlength="20" required /><br />
<label for="email">Email:</label><input type="text" name="email" required /><br />
<label for="confirm_email">Potvrdi email:</label><input type="text" name="confirm_email" required /><br />
<label for="ime">Ime:</label><input type="text" name="ime" required /><br />
<label for="prezime">Prezime:</label><input type="text" name="prezime" required /><br />
<label for="oib">OIB:</label><input type="text" name="oib" required /><br />
<label for="ulica">Ulica i kućni broj:</label><input type="text" name="ulica" required /><br />
<label for="mjesto">Mjesto i poštanski broj:</label><input type="text" name="mjesto" required /><br />
<br/>
<input type="submit" name="register" id="register" value="Registracija" />
</div>
</form>
<?php
}
?>
</div>
<?php include "footer.php";?>
</body>
</html>
Is it possible do that only with php or must be javascript or something else?
I've searched on forum and tried with this and similar code but it doesn't work.
<input type="text" name="login" value="<?php if(isset($_POST['login'])){ echo $_POST['login'];}?>">
I appreciate any help!
The $_POST['<value>'] doesn't work because of the redirect, it "drops" the $_POST data.
One way to achieve the desired functionality is to use $_SESSION when the form has been submitted you can store the values in the $_SESSION, or you might prefer to only store them if there's a error.)
You can store/save the values in $_SESSION like so:
$_SESSION['name'] = $_POST['name'];
And then simply check for the $_SESSION['<value>'] instead of the $_POST['<value>'].
<input type="text" name="login" value="<?php if(isset($_SESSION['login'])){ echo $_SESSION['login'];}?>">
You'd have to remember to start the session at the top of each page you want to use sessions on.
session_start();
One thing to be aware of is that you should unset the session values after you are done with them, so you avoid old data being reused.
There are plenty of ways you can use $_SESSION to achieve what you want so it's all about finding the way that suits you best.
You can read more about sessions here
best way is to create session array for complete data and if it is not empty show it in your fields. other method is to pass that post array back to your view when redirecting after invalid values.
hope you will understand.
If you just want the register.php script to fill the fields, simply send the needed info to this script:
$param = "?user=".urlencode($_POST['user']);
$param .= "&email=".urlencode($_POST['user']);
//...concat all needed param here
echo "&nbsp<p><a class='one' href=\"register.php".$param."\">Unesite drugo korisničko ime!</p>";
Then in your register.php script, just read the $_GET['...'] values to populate your form. don't forget to urldecode() them.
Note: For obvious security reasons, DO NOT pass the password in the GET parameters (nor store it in a $_SESSION variable).

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.

Categories