HTML Form PHP Post to Self to Validate or Submit to New Page

HTML form PHP post to self to validate or submit to new page

When all your conditions are met you can use header('Location: http:mywebsite.com/otherAction.php')

// 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: http://mywebsite.com/otherAction.php');
exit();
}
}

In some of my works, my setup is like this but I learned something not good here. That's when you refresh the page after submitting the form , POST values still remains and possible for duplicating entries. Which is not good IMO.

Submit form POST to another page but validate before redirect and keep on same page if validation fails

I will show you how this can be done via JavaScript/Ajax and PHP. I think it won't be difficult to learn doing it from this tutorial, but if some questions arise I am ready to help you.

JavaScript/Ajax request

First of all, we need to add "Submit" button to form and set "sendData()" function as its "onclick" listener. Which means each time you click on "Submit" button, "sendData()" function will execute. Also, we need to add 'class' attribute to 'number' and 'date' input elements, to get their values in more cleaner way.

<form method="post" id="orderform" action="somesite.com/shoppingcart">
<input type="number" class='myForm' name="numitems" id="numitems" value="1">
<input type="date" class='myForm' name="date" id="date">
<input type="Submit" value="Send" onclick = sendData(); return false;"/>
</form>

<script type="text/javascript">

function sendData()
{
var formElements = document.querySelectorAll(".myForm"); // We use 'class' attribute to get form elements (number and date).
var formData = new FormData(); // we create FormData object with which we can send data to "PHP" script (server side).
for(var i = 0; i < formElements.length; i++)
{
formData.append(formElements[i].name, formElements[i].value);
}
//AJAX Starts Here
var xmlHttp = new XMLHttpRequest(); // Create "ajax" object
xmlHttp.onreadystatechange = function() //This is to wait for response from your PHP script
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //And when status is OK use result
{
var responseText = xmlHttp.responseText; //here you save your response from server side.
if(responseText["Status"] === "OK") //if you send from server side that "Status" is OK, then you can go to that page
{
window.location.href = "somesite.com/shoppingcart";
}
else //otherwise you refresh page
{
window.location.reload();
}
}
}
xmlHttp.open("POST", "somesite.com/shoppingcart"); //set page value, where you want to send form values
xmlHttp.send(formData); //send actual data
}

</script>

PHP validation (to avoid manipulation/override on client-side)

When you validate values in server-side, set $_SESSION["Status"] = "OK".
After that if someone tries to "hack" your page and "change" your JavaScript functions to navigate to somesite.com/shoppingcart page, you will check:

somesite.com/shoppingcart

<?php
if($_SESSION["Status"] === "OK"])
{
//give permission
}
else
{
return false;
}
?>

PHP form validation and submit to another page

header('location:Processor.php'); sends the browser to another page, but not the POST values. Either do the functions in the same page, or use Sessions to pass data to another page. First option is recommended.

Form is submitting to another page without validation in php

To me it seems you are new to PHP form handling. For beginners reinventing the wheel and is dangerous as it's so easy to open up security flaws in your script. Use a framework or CMS that can handle forms for you (e.g., WordPress and Contact Form 7 or just use something easy as Zebra Form or something complete like CakePHP, Laravel or Symfony.

Just don't do everything yourself unless you really know what you are doing. It might take some time to get started, but it will definitely pay off in the long run.

Redirect to new page after PHP validation

Here is your code

<?php
$nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
$name = $tele = $email = $party = $vip = $reservation = $time = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter a full name";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid name entered";
}
}

if (empty($_POST["tele"])) {
$teleErr = "Please enter a telephone number";
} else {
$tele = test_input($_POST["tele"]);
if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
$teleErr = "Invalid telephone number entered";
}
}

if (empty($_POST["email"])) {
$emailErr = "Please enter an email address";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email entered";
}
}

if($_POST['party']=="") {
$partyErr = "Please select the party size";
} else {
$party = test_input($_POST["party"]);
}

if (empty($_POST["vip"])) {
$vipErr = "Please make a VIP area selection";
} else {
$vip = test_input($_POST["vip"]);
}

if (empty($_POST["reservation"])) {
$reservationErr = "Please enter the reservation date";
} else {
$reservation = test_input($_POST["reservation"]);
if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
$reservationErr = "Invalid reservation date";
}
}

if($_POST['time']=="") {
$timeErr = "Please select the reservation time";
} else {
$time = test_input($_POST["time"]);
}

if($nameErr == "" && $teleErr == "" && $emailErr == "" && $partyErr == "" && $vipErr == "" && $reservationErr == "" && $timeErr == ""){

header('Location: http://yoursite.com/dashboard');
exit();

}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

?>

html form using PHP_SELF & php validation - after submit, results displayed on new page without displaying form

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

$showHtml = true;

$month = $day = $year = "";

$monthErr = $dayErr = $yearErr = "";

$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";

function test_input($data) {

$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);

return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Month error & filter check code....

if (empty($_POST["month"])) {

$month = "";

} else {

$month = test_input($_POST["month"]);

if (!preg_match("/^[a-zA-Z ]*$/",$month)) {

$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";

}
}

// Day error & filter check code....

if (empty($_POST["day"])) {

$day = "";

} else {

$day = test_input($_POST["day"]);

if (!is_numeric($day)) {

$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";

}
}

// Year error & filter check code....

if (empty($_POST["year"])) {

$year = "";

} else {

$year = test_input($_POST["year"]);

if (!is_numeric($year)) {

$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";

}
}

if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {

$showHtml = false;

$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];

$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";

$result = $conn->query($sql);

if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";

// output data of each row

while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}

echo "</table>";

} else {

echo "<p id='no_results'>Sorry - No Results Found :( </p>";

}
}
}

$conn->close();

exit ();

?>

<?php

if ($showHtml)

{

?>

<!DOCTYPE html>

<meta charset="UTF-8">

<html>

<head>
</head>

<body>

<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

<select id="item_select" name="month">

<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>

</select>

  

<select id="item_select" name="day">

<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>

</select>

  

<select id="item_select" name="year">

<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>

<br>

<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>

<br>

<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>

</form>

</body>

</html>

<?php

}

?>


Related Topics



Leave a reply



Submit