I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>
Related
Using core PHP only and nothing else, like JavaScript or clientside programming, I need PHP to check if the form's required fields are filled in or not, and display error message if missed. I need to check using procedural style programming as I'm not into OOP yet and don't understand it.
Html Form
<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>
<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>
Php Form Validator
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels_count = count($required_labels);
for($i=0; $i!=$required_labels_count; $i++)
{
if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I don't know how to complete the code here.
{
echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
}
}
?>
I know I need to check against associated array values as it would be easier and less code, but I don't know how to do it.
Notice my error echo. It's incomplete as I don't know how to write that peace of code.
How would you check with the shortest possible code using procedural style?
Anything else I need to know?
NOTE: I do not want to be manually typing each $_POST[] to check if the required ones are filled in or not. I need PHP to loop through the $required_labels[] array and check. Or if you know of any shorter way of checking without looping then I want to know.
First we will have an empty $errors array, and then we will apply the validations, and if any of them fails, we will populate the $errors.
Finally using a helper function errorsPrinter we will print the errors under their labels.
For you PHP validation part use the below code. Note that I also added the part to validate the string and int types too.
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$inputs = $_POST;
$errors = [];
foreach($required_labels as $label) {
if(!isset($inputs[$label]) || empty($inputs[$label])) {
$errors[$label] = array_merge(
["You must fill-in the field."],
$errors[$label] ?? []
);
}
}
foreach($strings_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be string"],
$errors[$label] ?? []
);
}
}
foreach($ints_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be int"],
$errors[$label] ?? []
);
}
}
function errorsPrinter($errors, $key)
{
$output = '<ul>';
if(!isset($errors[$key])) {
return;
}
foreach($errors[$key] as $error) {
$output = $output. '<li>' . $error . '</li>';
}
print($output . '</ul>');
}
?>
inside the form you can do something like this:
<form method='POST' action="">
<?php errorsPrinter($errors, 'submission_id') ?>
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<?php errorsPrinter($errors, 'website_age') ?>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<?php errorsPrinter($errors, 'url') ?>
<label for='url'>url</label>
<input type='url' name='url' id='url' >
<br>
<?php errorsPrinter($errors, 'anchor') ?>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' >
<br>
<?php errorsPrinter($errors, 'description') ?>
<label for='description'>description</label>
<input type='text' name='description' id='description' >
<br>
<?php errorsPrinter($errors, 'keyphrase') ?>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' >
<br>
<?php errorsPrinter($errors, 'keyword') ?>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' >
<br>
<button type='submit'>Search!</button>
</form>
Note that the errorsPrinter is just a helper and you can remove it and use $errors array as you want. The sample output of errors is like this:
[
"url" => ["You must fill-in the field."],
"anchor" => ["You must fill-in the field."],
"description" => ["You must fill-in the field."],
"keyphrase" => ["You must fill-in the field."],
"keyword" => ["You must fill-in the field."],
"website_age" => ["This input should be int"]
]
$errors = [];
foreach($required_labels as $field) {
if (!isset($_POST[$field]) || $_POST[$field] == '') {
$errors[$field] = "{$field} cannot be empty";
// echo "${field} cannot be empty";
}
}
And then to output those errors:
<?php
if (count($errors)) {
?>
<div id='error_messages'>
<p>Sorry, the following errors occurred:</p>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
</div>
<?php
}
And you could directly output the errors next to the input as well:
<input type="text" id="first_name" name="first_name" placeholder="First Name" />
<?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>
I'm having a issue where a variable is becoming undefined when the page is loaded individually...
So.
My front page has a address form where when the address is filled out and you click "Get your offer" it'll take you to another page where the address is carried over using $_POST['address'] in the value of the new input. so value="<?php echo $_POST['address']; ?>"
My problem is that when the offer page is loaded without using the front page form it gives me the error
<br /><b>Notice</b>: Undefined index: address in <b>C:\xampp\htdocs\offer\index.php</b> on line <b>228</b><br />Address
which makes sense. so i tried to fix it by putting this in the value= :
<?php
$carryover = $_POST['address'] or empty($carryover);
if(empty($carryover)) {
echo 'Enter Address';
} else {
echo $carryover;
}
?>
which did absolutely nothing so.
Front page form:
<form method="post" action="/offer/index.php" name="front" id="front">
<div class="form-group">
<input type="text" id="autocomplete" onFocus="geolocate()" name="address" id="address" value="" placeholder="123 main st" required>
<button type="submit" class="theme-btn btn-style-nine"><span class="txt">Get your offer</span></button>
</div>
</form>
Form 2 on offer page (where address is carried over too):
<form class="multisteps-form__form" action="finish.php" id="wizard" method="POST" enctype="multipart/form-data">
<div class="col-lg-8">
<div class="form-input-inner position-relative has-float-label" >
<input type="text" name="address" id="address" placeholder="Address" value="<?php
$carryover = $_POST['address'];
if(empty($carryover)) {
echo 'Address';
} else{
echo $carryover;
}
?>
" class="form-control" required>
<label>Address</label>
<div class="icon-bg text-center">
<i class="fas fa-home"></i>
</div>
</div>
</div>
</form
The undefined index notice happens when you read $_POST['address'] so any code you write after that isn't going to affect the notice.
Checking whether $carryover is empty is too late, you need to check if the $_POST index itself is empty.
Instead of:
$carryover = $_POST['address'];
if(empty($carryover)) {
echo 'Enter Address';
} else {
echo $carryover;
}
You need to use:
if(empty($_POST['address']) {
echo 'Enter Address';
} else {
$carryover = $_POST['address'];
echo $carryover;
}
Instead of this:
$carryover = $_POST['address'] or empty($carryover);
use this:
$carryover = $_POST['address'] ?? '';
I am trying to create a simple tax calcualtor and need to validate the both textfields so they are not empty and it doesn't appear to be working any tips?
if(isset($_GET['taxSubmit'])) {
$afterPrice = $_GET['taxPrice'];
$taxRate = $_GET['taxRate'];
$beforeTax = ($afterPrice * 100) / ($taxRate + 100);
if(!empty($_GET['taxPrice'.'taxRate'])){
echo "<h1>Price before tax = £".$beforeTax."<h1>";
} else {
echo 'All Fields Required';
}
}
Somebody asked for the markup so here it is:
<form method="get" action="watWk5.php">
<fieldset>
<legend>Without tax calculator</legend>
<label for="">After Tax Price</label>
<input type="text" name="taxPrice"/ value=<?php
if(isset($_GET['taxPrice'])){
echo $_GET['taxPrice'];
}
?>>
<label for="">Tax Rate</label>
<input type="text" name="taxRate"/ value=<?php
if(isset($_GET['taxRate'])){
echo $_GET['taxRate'];
}
?>>
<input type="submit" value="Submit" name="taxSubmit"/>
<button type="reset" value="Reset" name="clrButton">Clear</button>
</fieldset>
Each variable should have its own !empty() check
if(!empty($_GET['taxPrice']) && !empty($_GET['taxRate'])) {
//proceed
} else {
//throw error
}
I have a form that users can utilize to introduce some data to create a badge. I'm using session so that i can keep like a little history list for the users, and also if they click on one element from that list the data will be sent to the form automatically. My problem is that when i click on one element from the list a new row is inserted containing the same data, and also if i complete the form with identical data that i already have in my list again it creates another line containing the same data that i already have once. Can i do something so that my history list to contain only unique values, basically to not have the same line multiple times.
This is my code for the form:
<form method="get" autocomplete="off">
<h3>Creaza ecuson</h3>
<label>
Nume:<br><input type="text" name="nume" id="nume" required value="<?php echo $search->nume ?>"><br>
Prenume:<br><input type="text" name="prenume" id="prenume" required value="<?php echo $search->prenume ?>"><br>
Sex:<br><div class="autocomplete" style="width:300px;">
<input id="sex" type="text" name="sex" required value="<?php echo $search->sex ?>">
</div><br><br>
Rol:<br><div class="autocomplete" style="width:300px;">
<input id="rol" type="text" name="rol" required value="<?php echo $search->rol ?>">
</div><br><br>
Culoare text:<br><input type="color" name="cul" id="cul" value="<?php echo $search->cul ?>"><br><br>
Font ecuson:<br><div class="autocomplete" style="width:300px;">
<input id="font" type="text" name="font" required value="<?php echo $search->font ?>">
</div><br><br>
Format ecuson (portrait or landscape):<br><div class="autocomplete" style="width:300px;">
<input id="format" type="text" name="format" required value="<?php echo $search->format ?>">
</div><br><br>
</label>
<input type="submit" name="history" value="History" />
<button type="button" onclick="create()">Creaza</button><br><br>
</form>
My session code:
<?php
session_start();
$search = parseRequest();
storeSearch($search);
include "form.php";
$searches = $_SESSION['searches'];
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty()) {
$_SESSION['searches'][] = $search;
}
}
function parseRequest() {
$search = new SearchRequest;
$search->nume = !empty($_GET['nume']) ? $_GET['nume'] : "";
$search->prenume = !empty($_GET['prenume']) ? $_GET['prenume'] : "";
$search->sex = !empty($_GET['sex']) ? $_GET['sex'] : "";
$search->rol = !empty($_GET['rol']) ? $_GET['rol'] : "";
$search->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$search->font = !empty($_GET['font']) ? $_GET['font'] : "";
$search->format = !empty($_GET['format']) ? $_GET['format'] : "";
return $search;
}
/**
* search request
*/
class SearchRequest
{
public $nume = "";
public $prenume = "";
public $sex = "";
public $rol = "";
public $cul = "";
public $font = "";
public $format = "";
function toQueryString() {
$params = [
'nume' => $this->nume,
'prenume' => $this->prenume,
'sex' => $this->sex,
'rol'=> $this->rol,
'cul'=> $this->cul,
'font'=> $this->font,
'format'=> $this->format
];
return http_build_query($params);
}
function isEmpty() {
return !$this->nume || !$this->prenume || !$this->sex || !$this->rol || !$this->cul || !$this->font || !$this->format;
}
}
?>
And the so called history code:
<?php
foreach ($searches as $s) {
?>
<li><a href="creare.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->nume?> - <?php echo $s->prenume?> - <?php echo $s->sex?> - <?php echo $s->rol?> - <?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?>
</a></li>
<?php
}
?>
I don't think the script with the autocomplete function needs to be posted here for the question that i asked. If needed i will provide.
perhaps something as simple as
function storeSearch($search) {
if (!isset($_SESSION['searches'])) {
$_SESSION['searches'] = [];
}
if (!$search->isEmpty() && !in_array($search,$_SESSION['searches') {
$_SESSION['searches'][] = $search;
}
}
Building on CFP Support's answer, here's a slightly different approach to how I would create the form and handler. It's very similar to yours but I structured the logic a bit differently. I only added 3 fields from your form but you can easily add the remaining fields.
Fiddle - http://phpfiddle.org/lite/code/354t-6sgn
<?php
session_start();
// Initialize the cart if it needs it.
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
// Should we show cart?
$showCart = isset($_GET['cart']) && $_GET['cart'] === 'true';
// Should we clear the cart?
if (isset($_GET['clear']) && $_GET['clear'] === 'true') {
$_SESSION['cart'] = [];
}
// Grab the current cart.
$cart = $_SESSION['cart'];
// The form was submitted
if (isset($_POST['submit'])) {
// Copy the POST data into a variable so we can modify it without side effects.
$formData = $_POST;
// Remove the submit button from the form data
unset($formData['submit']);
// Check if it is in the cart already.
if (!in_array($formData, $cart)) {
// If not, then add it.
$cart[] = $formData;
}
// Store the cart in the session.
$_SESSION['cart'] = $cart;
}
?>
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form method="post" autocomplete="off">
<h3>Creaza ecuson</h3>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="nume">Nume:
<input type="text" name="nume" id="nume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="prenume">Prenume:
<input type="text" name="prenume" id="prenume" class="form-control" required>
</label>
</div>
</div>
<div class="mb-3">
<div class="col-md-6 mb-3">
<label for="sex">Sex:
<input type="text" name="sex" id="sex" class="form-control" required>
</label>
</div>
</div>
<button class="btn btn-primary" name="submit" type="submit">Create</button>
<?php
// Toggle show/hide history
if ($showCart) { ?>
<a class="btn btn-primary" href="?" role="button">Hide Cart</a>
<?php } else { ?>
<a class="btn btn-primary" href="?cart=true" role="button">Show Cart</a>
<?php }
// If the cart is not empty, allow user to clear it.
if (!empty($cart)) { ?>
<a class="btn btn-primary" href="?clear=true" role="button">Clear Cart</a>
<?php }
?>
</form>
<?php
// Show the cart.
if ($showCart) {
echo '<pre>';
var_dump($cart);
echo '</pre>';
}
?>
</div>
</body>
</html>
Here's a way and little pseudo-code, you could implement something similar with your codebase.
The idea is, since from one computer only one person can sign up, store a unique ID for that person in session. Then when entering the data into session, check if that ID is present or not.
If it's present, do not add, if it's not, add.
Pseudo-code
$uniqueID = hash("sha256", $_SERVER['REMOTE_ADDR']); //generate a unique ID depending on IP since that would be unique for each computer
//insert into your session
if(!in($sessionHandler, $uniqueid)
{
//insert now
}
Here is my code:
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$age = $_POST['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_GET['getName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$age = $_GET['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
I have two forms. Both displaying the exact same thing, but one form using POST and one using GET.
I have gotten so close to finishing this off but now I have another small/weird issue.
The code technically works correctly, but here's the output explanation:
when I first open up the page the GET form already has the result "Sorry, try again when you're 16 or older." When I fill out the first 'simple' form, it displays the result correctly but then the POST form shows the "Sorry, try again..." result. Then, when I fill in the information and click submit, it displays the correct result and the other two forms are blank as they're supposed to be, and then the same result when I fill out the GET form.
Any help on this is much appreciated.
Try this code :
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
if (isset($_POST['firstName']) && $_POST['lastName'])
{
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
}
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_POST['postName']))
{
echo $_POST['postName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['age']))
{
$age = $_POST['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_GET['getName']))
{
echo $_GET['getName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if (isset($_GET['age']))
{
$age = $_GET ['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
Please try this. I hope it will help.
Replace
if ($_SERVER['REQUEST_METHOD'] == "POST") {
with
if (isset($_POST['age'])) {
Similarly,Replace
if ($_SERVER['REQUEST_METHOD'] == "GET") {
with
if (isset($_GET['age'])) {
When you first enter on page, default REQUEST_METHOD is GET so you should check if isset($_GET['age']) {
and here check if it is more than 16
}
also you should check this one
echo $_GET['getName']; and change on this
echo isset($_GET['getName']) ? $_GET['name'] : "";
You should also check $_POST request like this and your program will work correctly.