Submit and show results in the form in the same page - php

I've a form in which I want the calculate function to be called and displayed on the same page. If there is an error, it should display in the span tag on the same page.
Here's what I have right now, and I'm running into problems:
index.php [UPDATED]:
<?php
if (isset($_POST['submit'])) {
$bdmm = $_POST['bdmm'];
$sdmm = $_POST['sdmm'];
$strings = array(
$bdmm,
$sdmm,
$lgpm
);
if(!$bdmm){
$error = "Error";
exit();
}
elseif(!$sdmm){
$error = "Error";
exit();
}
//check whether the string is numeric
foreach ($string as $string) {
if (!preg_match("/^-?([0-9])+\.?([0-9])+$/", $string))
{
echo "Invalid entry. Please enter a number.";
}
}
$calc = new Calc();
if (isset($bdmm)) {
$calc->calculateMet($bdmm,$sdmm);
}
}
// Defining the "calc" class
class Calc {
private $vs = 0;
private $nob = 0;
private $tw = 0;
public function calculateMet($b,$s)
{
//code to calculate
//display nbnm in textbox
$nbnm = $nobr;
//display twkg in textbox
$tw = $nob * 25;
$twr = round($tw);
$twkg = $tw;
exit;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<!-- Begin Wrapper -->
<div id="wrapper">
<div id="column">
<form id="deps" name="deps" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<?php
if (isset($_REQUEST['error'])){
$err = $_REQUEST['error'];
?>
<div id="er"> <span class="er" > <?php echo $err; ?></span></div>
<?php } ?>
<table class="table">
<tr>
<td class="field head"> </td>
<td class="field cv"><label for="met">Metric</label></td>
<td class="field cv"><label for="eng">English</label></td>
</tr>
<tr>
<td class="field head"><label for="bd">Bore Dia.</label></td>
<td class="field"><input type="text" name="bdmm" id="bdmm" /><label for="bdmm">MM</label></td>
</tr>
<tr>
<td class="field head"><label for="sd">Screen Dia.</label></td>
<td class="field"><input type="text" name="sdmm" id="sdmm" /> <label for="sdmm">MM</label></td>
</tr>
<tr>
<td class="field head"><label for="nbn">No. of Bags needed</label></td>
<td class="field"><input type="text" name="nbnm" id="nbnm" value="<?php echo $nbnm; ?>" /></td>
</tr>
<tr>
<td class="field head"><label for="tw">Total Weight</label></td>
<td class="field"><input type="text" name="twkg" id="twkg" value="<?php echo $twkg; ?>" /> <label for="twkg">KG</label></td>
</tr>
</table>
<input type="submit" id="submit" value="Calculate" />
</form>
</div>
</div>
<!-- End Wrapper -->
</body>
</html>
There are mainly two things I want to show in the form:
1- If there is an error, it should display the error in the span tag -
<?php
if (isset($_REQUEST['error'])){
$err = $_REQUEST['error'];
?>
<div id="er"> <span class="er" > <?php echo $err; ?></span></div>
<?php } ?>
I did this^, but it does not throw any error even if the textbox is blank.
2- I want to show the calculated results in the textboxes in the form itself:
<td class="field"><input type="text" name="nbnm" id="nbnm" value="<?php echo $nbnm; ?>" /></td>
<td class="field"><input type="text" name="twkg" id="twkg" value="<?php echo $twkg; ?>" />
^This is throwing an error: Undefined variable nbnm and twkg
Where am I going wrong?

There are several problems with your code.
First, the variables that are established in the Calc class are not going to be directly accessible by code outside of the class declaration. Your code <?php echo $twkg; ?> is not going to work because of scope - the variable twkg does not exist in the global scope where you are outputting the HTML.
You can access those variables in the Calc class, but you've made them private. You will either have to make a getter method for those variables if they remain private (thus <?php echo $calc->getTwkg(); ?>) OR, make them public and access them using the arrow operator (thus <?php echo $calc->twkg; ?>).
As for the error message, for one, as has been pointed out, the post handling code needs to go above the form rendering code, otherwise the form will be rendered before the lower code has a chance to decide if there's an error or not. Second, I am not sure what the use of $_REQUEST['error'] is all about: set $error to false, check for errors, if there is one, stick the error message in it. Then your if looks like this:
if ($error !== false)
echo '<div id="er"><span class="er"> '.$error.'</span></div>';
Here are some general edits... you've got a lot of confusing stuff in there and I don't know what you're doing, so I just put this together in the way of a collection of tips. I suggest you use more descriptive variable names: instead of $nob and $bdmn, use $bore_diameter_minimum - that way it is easy to see what a variable should contain.
// Defining the "calc" class
class Calc {
private $vs = 0;
public $nob = 0; // note that this is public
private $tw = 0;
public function calculateMet($b,$s) {
// do your calculations here
$this->vs = $b * $s;
// use $this->vs, $this->nob to change the private variables declared above
if ($this->vs < $v)
return false;
// return true if the calculation worked
return true;
}
// use public getters to return variables that are private
public function getVs() {
return $this->vs;
}
}
$calc = new Calc();
$error = false;
if (isset($_POST['submit'])) {
$bdmm = isset($_POST['bdmm']) ? $_POST['bdmm'] : false;
$sdmm = isset($_POST['sdmm']) ? $_POST['sdmm'] : false;
if(
$bdmm == false ||
strlen($bdmm) < 1 ||
preg_match("/^-?([0-9])+\.?([0-9])+$/", $bdmm) == false
){
$error = "Invalid Bore Dia.";
}
if(
$sdmm == false ||
strlen($sdmm) < 1 ||
preg_match("/^-?([0-9])+\.?([0-9])+$/", $bdmm) == false
){
$error = "Invalid Screen Dia.";
}
if ($error !== false) {
$result = $calc->calculateMet($bdmm,$sdmm);
if ($result === false)
$error = 'Calculation failed';
}
}
// output an error message
if ($error !== false)
echo '<div class="error">'.$error.'</div>';
echo 'Private test: '.$calc->getVs();
echo 'Public test: '.$calc->nob;

You need to move the php code on top of the page, because you are accessing variables before even they are created.

You need to put $error somehow into the $_REQUEST (because you try to get it from there and it is not there automatically). You should use $_SESSION['error'] instead of $error = "Error!" and if (isset($_SESSION['error'])){ instead of if (isset($_REQUEST['error'])){ .
Move all the code from the bottom to the top. I haven't studied the code too closely, but it seems the script had no chance to set the variables before they were set.

Related

PHP form with multiple steps and validation

I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>
You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.

Warning: Missing argument 4 for renderForm()

Good morning/afternoon,
Can someone please explain to me why i keep getting a;
Warning: Missing argument 4 for renderForm(), called in /home/***/public_html/new.php
Here is the HTML/PHP code i am using;
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($date, $home, $time, $away, $city, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<label>Date:</label>
<input class="input" name="id" type="text" value="<?php echo $date; ?>">
<br/>
<label>Home Team:</label>
<input class="input" name="id" type="text" value="<?php echo $home; ?>">
<br/>
<label>Time:</label>
<input class="input" name="id" type="text" value="<?php echo $time; ?>">
<br/>
<label>Away Team:</label>
<input class="input" name="id" type="text" value="<?php echo $away; ?>">
<br/>
<label>Location:</label>
<input class="input" name="id" type="text" value="<?php echo $city; ?>">
<br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$home = mysql_real_escape_string(htmlspecialchars($_POST['home']));
$time = mysql_real_escape_string(htmlspecialchars($_POST['time']));
$away = mysql_real_escape_string(htmlspecialchars($_POST['away']));
$city = mysql_real_escape_string(htmlspecialchars($_POST['city']));
// check to make sure both fields are entered
if ($date == '' || $home == '' || $time == '' || $away == '' || $city == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($date, $home, $time, $away, $city, $error);
}
else
{
// save the data to the database
mysql_query("INSERT data SET date='$date', home='$home', time='$time', away='$away', city='$city'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
I have tried to search here and google with no fix. Can anyone please help me please? This should be a form to add new events. But with these errors i am unable to make it work. Thank you in advance for any assistance you might be able to provide.
The original part is done. Thank you for all the answers. But now i after i submit it gives me this error, not sure if it has anything to do with the edit i made to:
renderForm(null,null,null,null,null,null);
Thank you once again.
renderForm('','',''); down the bottom of your code is missing a 4th argument.
Your function is as follows:
function renderForm($date, $home, $time, $away, $city, $error){}
you require six total arguments to be passed to the function,
$date
$home
$time
$away
$city
$error
therefore you have to populate your function call with something for each of those
renderForm(null,null,null,null,null,null);
or you can use '' the empty string you show in your example. But something has to be passed for each argument.

PHP session array and input validation

Currently I am sending error messages and storing the value of my input fields in sessions.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductPrice']; unset($_SESSION['msgProductPrice']); ?></label>
<input type="text" name="product_price" value="<?php echo $_SESSION['val_ProductPrice']; unset($_SESSION['val_ProductPrice']); ?>" />
PHP
$Price = $_POST['product_price'];
$errorcount = 0;
if(empty($Price) === true){
$PriceErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductPrice'] = $Price;
$_SESSION['msgProductPrice'] = $PriceErrormsg;
}
This works perfectly with one of a kind input field. If I try with multiple input fields with the same name, it doesn't work.
Form example
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
<label class="errormsg"><?php echo $_SESSION['msgProductAmount']; unset($_SESSION['msgProductAmount']); ?></label>
<input type="text" name="product_amount[]" value="<?php echo $_SESSION['val_ProductAmount']; unset($_SESSION['val_ProductAmount']); ?>" />
This is where I'm unsure on how to validate all the input fields, how to keep the value in each input field when you hit submit and how to send an errormsg about each field?
PHP
$Amount= $_POST['product_amount'];
$errorcount = 0;
if(empty($Amount) === true){
$AmountErrormsg = "empty";
$errorcount++;
}
if($errorcount === 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrormsg;
}
If I understand your problem, multiple product amounts are being submitted, and you want to validate each one individually and display the error message next to the appropriate textbox?
Because you are receiving an array of values, you need to create a corresponding array of error messages.
It's a while since I've done any PHP, so this might not be 100% correct, but I think you need something along these lines...
$AmountErrorMessage = Array();
foreach ($Amount as $key => $value) {
if (empty($value)) {
$AmountErrorMessage[$key] = 'empty';
}
}
if ($AmountErrorMessage->count() > 0) {
// success
} else {
$_SESSION['val_ProductAmount'] = $Amount;
$_SESSION['msgProductAmount'] = $AmountErrorMessage;
}
You would then also need to iterate through the array in order to generate the HTML for your form, creating a label and input box for each value submitted.
This code help you to do it as per your wish..
<?php
session_start();
?>
<html>
<head>
<title></title>
<style>
.errormsg{
color:red;
}
</style>
</head>
<body>
<?php
if(isset($_POST['product_amount']))
{
$errorcount = 0;
for($i=0;$i<count($_POST['product_amount']);$i++){
$Amount[$i] = $_POST['product_amount'][$i];
if(empty($Amount[$i]) === true){
$_SESSION['msgProductAmount'][$i] = "empty";
$errorcount++;
}
else
$_SESSION['val_ProductAmount'][$i] = $Amount[$i];
}
if($errorcount === 0) {
unset($_SESSION['msgProductAmount']);
echo "success";
}
}
?>
<form action="" method="POST">
<?php
$cnt = 10;
for($i=0;$i<$cnt;$i++){
?>
<input type="text" name="product_amount[<?=$i?>]" value="<?php echo isset($_SESSION['val_ProductAmount'][$i]) ? $_SESSION['val_ProductAmount'][$i] : '';?>" />
<label class="errormsg"><?php echo $res = isset($_SESSION['msgProductAmount'][$i]) ? $_SESSION['msgProductAmount'][$i] : '' ; ?></label>
<br/>
<?php
}
?>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
<?php
unset($_SESSION['msgProductAmount'],$_SESSION['val_ProductAmount']);
?>

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

How to make a PHP Error message popup instead of new page? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Currently on my website I have a form in which once it is submitted, you're taken to a blank screen with the appreciation message.
Instead of moving to a new page, I wish to keep my users on the same page. How might I go about creating a popup and keeping the user within the same page?
You can use javascript validation or HTML5.
If you don't want these ways you can just open a popup window and set your form's target to it. Like this :
<form method="post" action="anything.php" onsubmit="window.open('','my_form_target', 'width=300,height=200', true); this.target='my_form_target';" >
...
try this for validation
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>

Categories