data cannot pass to another page after submitted - php

I wanted to pass the form data to another page after validate.
The user have to enter the correct data in order to proceed to next page.
I was trying to get the data from the first page but seems like it doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>
Register
</title>
</head>
<body>
<?php
// define variables and set to empty values
$firstNameErr = $surNameErr ="";
$firstName = $surName = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = true;
if (empty($_POST["firstName"])) {
$firstNameErr = "FirstName is required";
$valid = false;
} else {
$firstName = test_input($_POST["firstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surName"])) {
$surNameErr = "surName is required";
$valid = false;
} else {
$surName = test_input($_POST["surName"]);
// check if name only contain letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstNameErr = "Only letters and white space allowed";
}
}
if($valid){
header('Location: successReg.php');
exit();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
FirstName <input type="text" name="firstName" value="<?php echo $firstName;?>">
<span class="error">* <?php echo $firstNameErr;?></span>
<br><br>
SurName <input type="text" name="surName" value="<?php echo $surName;?>">
<span class="error">*<?php echo $surNameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
The code above shows the registration form.
After the "submit" button is pressed, it send to successReg.php
Here is the successReg.php code:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset = "UTF-8" />
<title> Register successfully</title>
</head>
<body>
<?php
/* Get each parameter value from the request stream and using ternary if operators check each parameter to see if it was set. If it is, store it in a variable. */
$firstName = filter_has_var(INPUT_POST, 'firstName');
$surName = filter_has_var(INPUT_POST, 'surName' );
$firstName = filter_var($firstName , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES );
$firstName = filter_var($firstName,FILTER_SANITIZE_SPECIAL_CHARS);
$surName = filter_var($surName , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES );
$surName = filter_var($surName,FILTER_SANITIZE_SPECIAL_CHARS);
echo" $firstName";
?>
</body>
</html>
In the last line of the successReg.php page, I'm trying get the data from the submitted page to see whether the data can be retrieved or not.
And also, the successReg.php page is supposed to insert all the data into the database.
The echo $firstName is for testing purpose, but seems it doesn't work.
If the data is successfully passed from the form page, I will only continue with the sql code.
Is there any mistake, or what am I missing?

You are sending the user to the success page without it knowing which values to show. You could do this a few ways.
When you send them to the new page, you could amend the latest database insert id and then pick up the result on the success page (not than you have that active yet), or
You could just pass the values directly as a GET and display them on the success page.
Such as:
if($valid){
echo 'Continue on';
exit();
}

Related

how to fix error of empty $_POST['name']

I want to have a form with php. but for many hours I'm involved an error and the error is when $_POST=['name'] wants to be checked empty or not it is empty.
When I check the database the row is white and nothing is there.
for checking if the $_POST is empty or not I print word 'empty' to be determined it's empty and it will be printed 'empty';
where is my mistake is it related to database mysql or not just in code?
please help me I got confused and bored.
this is whole of my codes:
<!doctype html>
<html lang="fa">
<head>
<meta charset="utf-8">
<title>form</title>
<link href="addContact.css" rel="stylesheet"/>
<link href="main.css" rel="stylesheet"/>
<link href="table.css" rel="stylesheet"/>
</head>
<body>
<?php
$name = "";
$nameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo 'empty';
$nameErr = "Name is required";
} else {
echo 'full';
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO abc (firstname)
VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
thank you in advance
The problem is in use of empty()
You can use it on variables not on values.
See here for PHP documentation page.
To check this, first save it in another variable and then check:
$tempVal = $_POST["name"];
if (empty($tempVal))
you can use this simple example
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
i suggest this:
Understanding $_SERVER['PHP_SELF']

Unable to throw error Message

registration_form
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
You do
require('validation.php');
setting and checking alot of variables e.g.
$name = test_input($_POST["name"]);
$nameErr = "Only letters and white space allowed";
come back from require and overwrite $name with original posted values and do nothing with $nameErr
$name = $_POST['name'];
check the errors after the require
e.g.
require('validation.php');
$lsError = $nameErr . $emailErr . $userErr . $passwordErr;
if(trim($lsError) != '') {
echo $lsError ."<BR>";
echo "ALL FIELDS ARE NECESSARY";
}
else {
//rest of your insert
}

PHP Session not recognizing variable when heading to another page

So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/> 
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>
you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>
You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.
Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here

Previous data auto insert when browser reloading in PHP

I have some data input area.Here is my file.
Here is my db.php:
<?php
$username = "root";
$password = "";
try {
$db = new PDO('mysql:host=localhost;dbname=task', $username, $password);
echo "Connection Successfull";
} catch (PDOException $e) {
die("Error: Database connection");
}
?>
And my index.php is:
<?php
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" value="Submit">
</form>
</div>
<?php
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
?>
</body>
</html>
When i first go to index.php page then it's showing some notice.
Notice: Undefined index: name in
C:\xampp\htdocs\techmasters\begin\index.php on line 21
Notice: Undefined index: email in
C:\xampp\htdocs\techmasters\begin\index.php on line 22
Notice: Undefined index: website in
C:\xampp\htdocs\techmasters\begin\index.php on line 23
but if i input any data then it going to be inserted fine.My problem is that if i reload the browser then previous inserted data going to inserted again.How can i solve this problem?
Thanks in advanced.
Its because, you are not checking whether form is submitted or not.
On every page request, data is getting inserted, add a check.
<?php
if (isset($_POST['name']) && ! empty($_POST['name'])) {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if (empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
$_POST = NULL;
}
?>
This will ensure that database insert will be done only in case of form submit.
EDIT:
If you submit a form to same page and then reload the page, it will
ask you to resubmit the form. Either change method to get and check
for duplicity or submit the form to another file (move form submit
code to other file and set it as form action).
When you reload the page it's asking for form re-submission. When you click on resend then it will post all data again and inserted in database. To overcome this issue you can use jquery.
Try this code :
html file :
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" id="frm" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" class="sub" value="Submit">
</form>
</div>
<script>
$(".sub").click(function (e) {
e.preventDefault();
$.post("test.php",$("#frm").serialize(),function(data){
if(data == "Inserted!") {
//You can reload your page here
} else {
//Display error message.
}
});
});
</script>
</body>
</html>
You php code (test.php) :
<?php
include "db.php";
if(isset($_POST['name']) && $_POST['name'] != "") {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
} else {
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
exit;
}
?>
Don't forget to add jquery file in your html.

stop repeat the actions on the page after submit the form

Stop repeat the actions on the page after submit the form
I made this "sign in" form and made a error messages to appear if the fields is empty and other error messages.
my request is:
After the "sign in" fails how to stop the fields from resubmit the values again when hit F5 or reload the page.
<?php
ob_start();
session_start();
include "config/config.php";
include "includes/functions/check.php";
$userName = $passWord = "";
$userNameErr = $passWordErr = $loginErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[a-zA-Z ]*$/", $userName)) {
$userNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['password'])) {
$passWordErr = "Password is required";
} else {
$passWord = check_input($_POST['password']);
}
$loginUser = $db->prepare("SELECT * FROM hired_person_info WHERE user_name=? AND password=?");
$loginUser->bind_param('ss', $userName, $passWord);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$_SESSION['name'] = $row->full_name;
$_SESSION['log'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "Invalid Login Information";
}
}
}
ob_flush()
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Administration Panel</title>
<link href="../css/adminStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 id="head" class="header_height"></h1>
<div class="contentLogin">
<div class="login_bg">
<div id="header">
<p>login</p>
</div>
<div id="form">
<?php
echo $loginErr;
?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="user_name" class="text_login">User name</label>
<input type="text" name="user_name" id="user_name" value="<?php echo $userName ?>">
<?php echo $userNameErr; ?>
<br/><br/>
<label for="password" class="text_login">Password</label>
<input type="password" name="password" id="password">
<?php echo $passWordErr; ?>
<br/>
<div id="submit">
<input type="submit" value="Sign in" name="submit" id="submit" class="btn">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Instead of using if($_SERVER["REQUEST_METHOD"] == "POST"){ try using the post name of your submit button. So the condition will be as follows,
if(isset($_POST['submit'])) {
}
Within this you can put all your codes. I am not telling that the condition you have used is wrong, but it may create conflict when you will put another form in the same page.
And after your operation completed, success or fail, does not matter just unset the post variable.
unset($_POST);
To completely avoid the resend functionality you need to redirect your page to the same page once. For that just save your error message in session and redirect to login page again. Then checking if session value for message exists then display your message.

Categories