what wrong with my testing2.php - php

here is my php form code...
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
// define variables and set to empty value
$firstNameError = "";
$lastNameError = "";
$error = false;
// if firstName is empty, make it NULL, else, test_input() the data.
$firstName = empty($_POST["firstName"]) ? NULL : test_input($_POST["firstName"]);
// if lastName is empty, make it NULL, else, test_input() the data.
$lastName = empty($_POST["lastName"]) ? NULL : test_input($_POST["lastName"]);
if (isset($_POST["submittingForm"])) {
/// CHECK FIRST NAME ERRORS
if ($firstName === NULL) {
// firstName is empty
$firstNameError = "First name is required!";
$error = true;
} else {
// check characters
if (!preg_match("/^[a-zA-Z ]*$/", $firstName)) {
$firstNameError = "Only letters and white spaces allowed!";
$error = true;
}
}
/// CHECK LAST NAME ERRORS
if (!preg_match("/^[a-zA-Z ]*$/", $lastName)) {
// check characters
$lastNameError = "Only letters and white spaces allowed!";
$error = true;
}
// if no error then redirect
if (!$error) {
$_SESSION['fistName'] = $firstName;
$_SESSION['lastName'] = $lastName;
header('Location: testing2.php');
exit();
}
} else {
// user did not submit form!
}
// clean input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<form id="userdetail" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="firstName">First Name: </label>
<input type="text" name="firstName" id="firstName" value="<?php echo $firstName; ?>">
<span class="error">* <?php echo $firstNameError;?></span>
<label for="lastName">Last Name: </label>
<input type="text" name="lastName" id="lastName" value="<?php echo $lastName; ?>">
<span class="error">* <?php echo $lastNameError;?></span>
</p>
<p>
<input type="submit" name="submittingForm" value="submit">
</p>
</fieldset>
</form>
</div>
</body>
</html>
and so here is my testing2.php which get the data after submited...
<?php
session_start();
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
echo "<h1>Successfull submission :</h1>";
echo "<p>fitstName : $firstName <p/>";
echo "<p>lastName : $lastName <p/>";
?>
when the form is submited , Notice: Undefined index: firstName in F:\xampp\htdocs\en407b\assigment\testing2.php on line 5 is appear...
i've tried to fix it but still cnt get it right...
pls help me....

change like this
if (!$error) {
$_SESSION['firstName'] = $firstName;//error here
$_SESSION['lastName'] = $lastName;
header('Location: testing2.php');
exit();
}

You have a simple typo -
if (!$error) {
$_SESSION['fistName'] = $firstName;
should be:
if (!$error) {
$_SESSION['firstName'] = $firstName;
I'd also recommend giving your form an action:
<form id="userdetail" action="testing2.php" method="POST">
and then move all the form processing logic over into that file. That would eliminate the need for a header redirect.

You have typo in your session name. You are assigning session to $_SESSION['fistName'] and trying to access it with $_SESSION['firstName'];

Related

php special character validation

I made a simple form where the user needs to enter their name and email adress, after the user has
done this they should click on the submit button and their data show for 3 seconds and after that they will be redirected to another page.
All this works but now i want to add a input validation i found a example on W3Schools and tried make this and add this to my code. Right now my code looks like this but the validation doesnt work. how can i fix this problem?
the validation doesnt show up so when a user for example puts a 2 behind his/her name the code wont give the error message: $NameErr = "only letters and white space are allowed"; instead of show this it goes straight to the "next page" were the user input is show for a short time
<?php
$NameErr = "";
$Message = false;
$Name = $_POST["Fullname"];
$Email = $_POST["Email"];
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["Fullname"])){
$NameErr = "name is required";
}else{
$Message = "your data has been sent, you will be forwarded to the next page.";
$Name = $_POST["Fullname"];
}
$Name = Input($_Post["Fullname"]);
if(!preg_match("/^[a-zA-Z-' ]*$/",$Name)){
$NameErr = "only letters and white space are allowed";
}
}
if(empty($_POST["Email"])){
$EmailErr = "Email is required";
}else{
$Message = "your data has been sent, you will be forwarded to the next page.";
$Email = $_POST["Email"];
}
$Email = Input($_Post["Email"]);
if(!filter_var($Email, FILTER_VALIDATE_EMAIL)){
$EmailErr = "Only letters are allowed";
}
function Input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>form</title>
<link rel="stylesheet" type="text/css" href="formulier.css">
</head>
<body>
<main>
<?php
if(!$Message){
?>
<p> put your data here: </p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<span class="error">* <?php echo $NameErr;?></span>
<input type="text" name="Fullname" placeholder="enter your fullname">
<span class="error">* <?php echo $EmailErr;?></span>
<input type="email" name="Email" placeholder="enter your email">
<button name="SubmitBtn">submit</button>
</form>
<?php
}else{
?>
<h1 id="Message"> your data is:</h1>
<p><b>Naam:</b> <?php echo $Name; ?></p>
<p><b>E-mail:</b> <?php echo $Email; ?></p>
<p id="Message"><?php echo $Message; ?></p>
<script>
var Message = document.getElementById("Message");
setTimeout(function(){
window.location = "contact.php";
}, 3000);
</script>
<?php
}
?>
</main>
</body>
</html>

php data validation submitting bad data

I currently have my code working to some state.
When the user inputs data name, email and company they submit the form and it will echo the inputs out which is fine, but when I enter invalid data into the form and submit it will still post but displays the else statement.
Have I missed something in my Preg_match or is this just a bad way to code the validation?
<!DOCTYPE html>
<html>
<head>
<title>Visitor Sign in</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="visitor.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<img src="Wincanton.png" alt="wincantonLogo" class="wincantonLogo" />
<img src="Screwfix.png" alt="screwfixLogo" class="screwfixLogo" />
<div style="clear:both"></div><br>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $companyErr = "";
$fullname = $email = $company = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
} else {
$fullname = test_input($_POST["fullname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fullname)) {
$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 (!preg_match("/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["company"])) {
$companyErr = "Name is required";
} else {
$company = test_input($_POST["company"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$company)) {
$companyErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Visitor Sign in</h1><br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="fullname" >
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Company: <input type="text" name="company">
<span class="error"><?php echo $companyErr;?></span>
<br><br>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fullname;
echo "<br>";
echo $email;
echo "<br>";
echo $company;
echo "<br>";
?>
</body>
</html>
try if isset condition.
if(isset($_POST['submit'])){
}

PHP Single Page Form Validation HTML - form not validating

PHP portion, where variables are initialized and set to empty. As well as the post methods and isset functions
The functions seem to be right, no errors when running the code. However, nothing is processed when the user submits everything. This is just a small portion of the code.
<?php
//define variables and set them to empty values
$fname_error= $phone_error= $address1_error= $address2_error= $city_error= $state_error= $zipcode_error= "";
$fname= $phone= $address1= $address2= $city= $state= $zipcode= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "Missing";
}
else {
$fname = test_input($_POST["fname"]);
//now we check to see that the name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fname_error = "Please use letters and white space only";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The Html portion:
<div class="userinput">
<label for="fname"><b>First Name</b></label>
<input type="text" name="fname" value="<?php
echo $fname ?>">
<span class="error">
<?php echo $fname_error;?></span>
</div>
Close the conditional REQUEST_METHOD.
Your code should look like this:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//define variables and set them to empty values
$fname_error = $phone_error = $address1_error = $address2_error = $city_error = $state_error = $zipcode_error = "";
$fname = $phone = $address1 = $address2 = $city = $state = $zipcode = "";
//flag to validate and allow SQL insert if true
$valid=true;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "Missing";
$valid=false;
} else {
$fname = test_input($_POST["fname"]);
//now we check to see that the name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $fname)) {
$valid=false;
$fname_error = "Please use letters and white space only";
}
}
}
//filter your input for security reason
function test_input($data) {
$data1 = trim($data);
$data2 = stripslashes($data1);
$data3 = htmlspecialchars($data2);
return $data3;
}
if($valid){
//Add you insert SQL
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="fname"><b>First Name</b></label>
<input type="text" name="fname" value="<?php echo $fname ?>">
<span class="error">
<?php echo $fname_error; ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//For testing porpuses:
echo "<h2>Your Input:</h2>";
echo $fname;
?>
</body>
Reference: https://www.w3schools.com/php/php_form_complete.asp
Form validation

Can't validate and display errors in PHP

I am trying to display form information with Shipping Information Heading, with validation of name, contact etc. I am able to display it but not able to validate it and if I submit a form blank it shows blank values except payment and shipping method are displaying with default values selected and one more thing it is not showing errors i.e; fname is required, I am confused a little bit. Can anyone add one things that if anyone post blank form it redirect it to again to form2.php page?
This is my form2.php page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="welcome2.php" method="post">
<label>First name: </label>
<input type="text" name="fname"><br>
<label>Lastname name: </label>
<input type="text" name="lname"><br>
<label>Email: </label>
<input type="email" name="email"><br>
<label>Contact No </label>
<input type="text" name="cno"><br>
<label>Address </label>
<input type="text" name="addr"><br>
<label>City </label>
<input type="text" name="city"><br>
<label>State </label>
<input type="text" name="state"><br>
<label>Country </label>
<input type="text" name="country"><br>
<label>Zip Code </label>
<input type="text" name="zipcode"><br>
<label>Credit Card Number </label>
<input type="text" name="ccno"><br>
<label>Payment Option </label>
<select name="Payment_option">
<option value="Cash On Delivery">Cash On Delivery</option>
<option value="Online">Online</option>
</select> <br>
<label>Shipping Method </label>
<select name="Shipping_Method">
<option value="TCS">TCS</option>
<option value="Leapord">Leapord</option>
<option value="FEDEX">FEDEX</option>
</select> <br>
<button type="submit" name="sub">Submit</button>
</form>
<?php
if(isset($_SESSION['errors']))
{
foreach($_SESSION['errors'] as $key => $error)
{
echo $error."<br>";
}
unset($_SESSION['errors']);
}
?>
</body>
</html>
and this is my welcome2.php page
<?php session_start();
$fname = "";
$lname = "";
$email = "";
$cno = "";
$addr = "";
$city = "";
$state = "";
$country = "";
$zipcode = "";
$ccno = "";
extract($_POST);
$errors = array();
if(isset($_POST['fname'])){
$_SESSION['fname'] = $_POST['fname'];
}if(isset($_POST['lname'])){
$_SESSION['lname'] = $_POST['lname'];
}if(isset($_POST['email'])){
$_SESSION['email'] = $_POST['email'];
}if(isset($_POST['cno'])){
$_SESSION['cno'] = $_POST['cno'];
}if(isset($_POST['addr'])){
$_SESSION['addr'] = $_POST['addr'];
}if(isset($_POST['city'])){
$_SESSION['city'] = $_POST['city'];
}if(isset($_POST['state'])){
$_SESSION['state'] = $_POST['state'];
}if(isset($_POST['country'])){
$_SESSION['country'] = $_POST['country'];
}if(isset($_POST['zipcode'])){
$_SESSION['zipcode'] = $_POST['zipcode'];
}if(isset($_POST['ccno'])){
$_SESSION['ccno'] = $_POST['ccno'];
}
if(isset($_POST['sub']))
{
if(!$fname)
$errors[] = "First name is required";
}
if(!$lname)
{
$errors[] = "Last name is required";
}
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$errors = "Only letters and white space allowed";
}
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$errors = "Only letters and white space allowed";
}
if(!$email)
{
$errors[] = "Email is required";
}
if(!$cno)
{
$errors[] = "Contact is required";
}if (strlen($cno)<=5)
{
$errors[] ="Contact contain more than 11 characters";
}
if(!$addr)
{
$errors[] = "Address is required";
}
if(!$city)
{
$errors[] = "City is required";
}
if(!$state)
{
$errors[] = "State is required";
}
if(!$country)
{
$errors[] = "Country is required";
}
if(!$zipcode)
{
$errors[] = "Zip Code is required";
}
if(!$ccno)
{
$errors[] = "Credit Card Number is required";
}?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1> Shipping Information </h1>
<?php echo $fname; echo "<br>";
echo $lname; echo "<br>";
echo $email; echo "<br>";
echo $cno; echo "<br>";
echo $addr; echo "<br>";
echo $city; echo "<br>";
echo $state; echo "<br>";
echo $country; echo "<br>";
echo $zipcode; echo "<br>";
echo $ccno; echo "<br>";
$option1 = isset($_POST['Payment_option']) ? $_POST['Payment_option'] : false;
if ($option1) {
echo htmlentities($_POST['Payment_option'], ENT_QUOTES, "UTF-8");
} else {
echo "Payment Method is required";
} echo "<br>";
$option2 = isset($_POST['Shipping_Method']) ? $_POST['Shipping_Method'] : false;
if ($option2) {
echo htmlentities($_POST['Shipping_Method'], ENT_QUOTES, "UTF-8");
} else {
echo "Shipping Method is required";
}
?>
You set the values at the top of the PHP file, so they are always set. Then the errors never trigger because you do not check if the $_POST[<value>] is set and then assign it to the variable.
Also, try to use loops. It helps with code maintenance and readability. Something like this could work for you:
$values = [
'fname' => 'First Name',
'lname' => 'Last Name',
'email' => 'Email',
'test' => 'testt',
];
$results = array();
$errors = array();
foreach ( $values as $name => $displayName ) {
if ( isset( $_POST[ $name ] ) )
{
$results[ $name ] = $_POST[ $name ];
}
else
{
$errors[] = $displayName . ' is required';
}
}
Your errors are being added with a faulty check. Use empty($variable) instead of the NOT operator (!).
Also, be careful how you are changing the value of your original empty variables.. I would use extract( $_POST, EXTR_OVERWRITE, 'form_' ); to be even safer and then reference by $form_fname, etc. Then use the empty() check.
I also recommend using a debugger that can step through each line with you. It works wonders.

How to $_Post data from submit form PHP after validation

I just saw this codes from this website and thinking to implement it to my project however I cannot get my data on the next page. I am using the test.php as a index and submit.php as a page that will catch the post
here is the codes
test.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.
if (empty($_POST["firstName"])) {
$firstNameErr = "First name is required";
$valid = false; //false
}
else {
$firstName = test_input($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
$valid = false;
}
else {
$lastName = test_input($_POST["lastName"]);
}
//if valid then redirect
if($valid){
header('Location: submit.php');
exit();
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Find Customer</h2>
<p><span class="error">* required</span></p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
First Name: <input type="text" name="firstName" value="<?php echo $firstName; ?>"><span class="error">* <?php echo $firstNameErr; ?></span><br><br>
Last Name: <input type="text" name="lastName" value="<?php echo $lastName; ?>"><span class="error">* <?php echo $lastNameErr; ?><br><br>
<input type="submit">
</form>
</body>
</html>
submit.php
<?php
$test=$_POST['lastName'];
echo $test;
?>
Your form action should be the file where you want to get the form submitted values .
change this <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post"> to <form action="submit.php" method="post">

Categories