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'] ?? '';
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I don't know what I did wrong on my code, the error message for php form validation stopped working.
It was working perfectly until i added value attribute to the input so that the user input will persist even if the page refresh and didn't deliver due to typeError.
The form does'nt show any error again but my reason for adding the value attribute is working.
I'm learning php, please help me to understand why i'm having the issue.
I don't understand because i'm not getting any error from php.
This is my code
<?php
// empting the value variables when user have'nt typed anything to prevent error. This is the shorthand of typing samething that's going to have the same value
$email = $title = $ingredients = '';
// put out the error on the html instead of echoing it
// so i used array so that i can neatly put out all the errors instead of using different variables for all
$error = array('email' => '', 'title' => '', 'ingredients' => '');
// check if the form was clicked and retrive the values sent
// i will achieve this by using a default method called isset() and i will check if value is contained in the form using the submit btn, this is because when a user clicks on the form submit, the user have entered a value
if(isset($_POST['submit'])){
// check if the field submited is empty
// we achieve this using a default method called empty()
// we check them one field at a time
// check for email
if(empty($_POST['email'])){
$error['email'] = ' Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if(empty($_POST['title'])){
$error['title'] = ' Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if(empty($_POST['ingredients'])){
$error['ingredients'] = ' Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php'?>
<form action="form.php" method="POST">
<div class="input_div">
<label >Email :</label>
<input type="text" name="email" value=" <?php echo $email ?> ">
<div class="error_msg"><?php echo $error['email']; ?></div>
</div>
<div class="input_div" >
<label >Pizza Title :</label>
<input type="text" name="title" value=" <?php echo $title ?> " >
<div class="error_msg"><?php echo $error['title']; ?></div>
</div>
<div class="input_div" >
<label >Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value=" <?php echo $ingredients ?> ">
<div class="error_msg"><?php echo $error['ingredients']; ?></div>
</div>
<div class="input_div" >
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Other then the issues with whitespace in your inputs you should also be aware of XSS when inserting the values back into the form (like using " would break the form) and also don't populate the errors till needed, this will allow you to easily continue and do the success step without needing to loop over the $errors array and it also allows you to hide the <div class="error_msg"></div> element and only show when there is an error.
Also your missing <head> and <body>, presuming they are in the includes, but doing it that way would make it rather difficult to add additional elements or scripts.
<?php
$email = $title = $ingredients = '';
$error = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check for email
if (empty($_POST['email'])) {
$error['email'] = 'Email is empty';
} else {
$email = $_POST['email'];
}
// check for title
if (empty($_POST['title'])) {
$error['title'] = 'Title is empty';
} else {
$title = $_POST['title'];
}
// check for ingredients
if (empty($_POST['ingredients'])) {
$error['ingredients'] = 'Ingredients is empty';
} else {
$ingredients = $_POST['ingredients'];
}
if (empty($error)) {
// do some thing with $email, $title, $ingredients
die(header('Location: ./thank-you.php'));
}
}
function xss_safe($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?><!DOCTYPE html>
<html lang="en">
<?php include 'template/header.php' ?>
<form action="form.php" method="POST">
<div class="input_div">
<label>Email :</label>
<input type="text" name="email" value="<?= xss_safe($email) ?>"/>
<?= isset($error['email']) ? '<div class="error_msg">'.$error['email'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Pizza Title :</label>
<input type="text" name="title" value="<?= xss_safe($title) ?>"/>
<?= isset($error['title']) ? '<div class="error_msg">'.$error['title'].'</div>' : '' ?>
</div>
<div class="input_div">
<label>Ingredients (comma seperated) :</label>
<input type="text" name="ingredients" value="<?= xss_safe($ingredients) ?>"/>
<?= isset($error['ingredients']) ? '<div class="error_msg">'.$error['ingredients'].'</div>' : '' ?>
</div>
<div class="input_div">
<input type="submit" class="submitBtn" name="submit" value="Submit">
</div>
</form>
<?php include 'template/footer.php' ?>
</html>
Seeing as your error checking is merely for empty/missed input fields it's easier to just make the inputs required as per HTML5. Here's a simplified version using placeholders for information after the form has been submitted.
Warning: If you are going to be inserting this data into a MySQL table, you need to sanitize the inputs first!
<?php
$email = $title = $ingredients = "";
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$title = $_POST["title"];
$ingredients = $_POST["ingredients"];
}
echo "
<form method='POST'>
<label>Email:</label>
<input type='email' name='email' placeholder='$email' required>
<label>Pizza Title:</label>
<input type='text' name='title' placeholder='$title' required>
<label>Ingredients (comma seperated):</label>
<input type='text' name='ingredients' placeholder='$ingredients' required>
<input type='submit' name='submit' value='Submit'>
</form>
";
?>
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>
While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';
I am having a problem, since my website reloads each time somemone submit a form.
It's a wide scroll, so i just found also another solution, but gives me an error.
PHP CODE:
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
if(isset($_SESSION['sent']))
{
$success='<h1>Thank you!</h1>';
unset($_SESSION['sent']);
header('Location: index.php#5');
}
?>
FORM CODE:
<form class="demo-form" name ="demo-form" data-parsley-validate method="post" action="submit.php" >
<ul>
<li class="js-hide-label">
<label for="name">Nombre:</label>
<input type="text" placeholder="Nombre" id="name" name="name" data-parsley-trigger="change" required tabindex="1" autocomplete="off" value="<?php echo (isset($_SESSION['post']['name']) ? $_SESSION['post']['name'] : ''); ?>" >
</li>
<li class="js-hide-label">
<label for="email">Your Email:</label>
<input type="email" placeholder="Your Email" id="email" data-parsley-trigger="change" name="email" autocomplete="off" required tabindex="2" value="<?php echo (isset($_SESSION['post']['email']) ? $_SESSION['post']['email'] : ''); ?>">
</li>
<li class="js-hide-label">
<label for="message">Message:</label>
<textarea placeholder="Messageā¦" id="message" name="message" tabindex="3" required data-parsley-trigger="keyup" textarea id="message" data-parsley-minlength="20" data-parsley-maxlength="100" data-parsley-minlength-message = "Come on! You need to enter at least a 20 caracters long comment.." data-parsley-validation-threshold="10"><?php echo (isset($_SESSION['post']['message']) ? $_SESSION['post']['message'] : ''); ?></textarea>
</li>
<input class="btn btn-default"type="submit" name="button" id="button" value="Submit" />
</ul>
<?php echo isset($success)?$success:''; ?>
</form>
As you can see, adding a POSSIBLE SOLUTION with header('Location: index.php#5'); makes my website come back to the contact form (not exactly what I wanted, but helps a bit), but it breaks the $success='<h1>Thank you!</h1>';.
Is there any easy way to do it (using my original code) with AJAX? Since I am not used to work with scripts.
In the other hand, could be a solution on display $success='<h1>Thank you!</h1>'; and make the function header('Location: index.php#5'); work on the same form?
Use Ajax to post data if you don't want to refresh the page.
See documentation here
$.post documentation
Or
Ajax
Use header and redirect the page.
header("Location:your_page.php");
You can redirect to same page or different page.
or
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
if(isset($_SESSION['sent']))
{
unset($_SESSION['sent']);
header('Location: index.php?msg=sucess');
}
if ( isset($_GET['msg']) && $_GET['msg'] == 'sucess' )
{
$success='<h1>Thank you!</h1>';
}
You can try this :-
By using session :
if(isset($_SESSION['sent']))
{
unset($_SESSION['sent']);
$_SESSION['thanks_msg'] = 'Thank You';
header('Location: index.php#5');
}
?>
On index.php file :-
check if the $_SESSION['thanks_msg'] is set or not, if set then displaythat session msg.
By using GET method :-
if(isset($_SESSION['sent']))
{
$success='Thank you!';
unset($_SESSION['sent']);
header('Location: index.php?msg='.$success);
}
?>
on index.php file
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}
EDIT :-
if(isset($_SESSION['sent']))
{
$success='Thank you!';
unset($_SESSION['sent']);
header('Location: index.php?msg='.$success);
}
?>
on index.php file
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}
I have the following error:
Notice: Undefined index: submit in C:\wamp\www\registration\register.php on line 6
Can't seem to work out whats wrong??? Here's the code::
<?php
//Create registration form (register.php)
include "../includes/db_connect.php";
if(!$_POST['submit']) ///Line 6
{
?>
<html>
<head><link rel="stylesheet" href="style.css"></head>
<div class="divider">
<strong>Register</strong><br/><br/>
<form method="post" action="register.php">
<div class="formElm">
<label for="first">First Name</label>
<input id="first" type="text" name="first">
</div>
<div class="formElm">
<label for="last">Last Name</label>
<input id="last" type="text" name="last">
</div>
<div class="formElm">
<label for="username">Desired Username</label>
<input id="username" type="text" name="username">
</div>
<div class="formElm">
<label for="password">Password</label>
<input id="password" type="password" name="password">
</div>
<div class="formElm">
<label for="pass_conf">Confirm Password</label>
<input id="pass_conf" type="password" name="pass_conf">
</div>
<div class="formElm">
<label for="email">Email</label>
<input id="email" type="text" name="email">
</div>
<div class="formElm">
<label for="about">About</label>
<textarea id="about" cols="30" rows="5" name="about">Tell us about yourself</textarea>
</div>
<input type="submit" name="submit" value="Register">
</form>
or Login
</div>
</html>
<?php
}
else
{
$first = protect($_POST['first']);
$last = protect($_POST['last']);
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$pass_conf = protect($_POST['pass_conf']);
$email = protect($_POST['email']);
$about = protect($_POST['about']);
$errors = array();
$regex = "/^[a-z0-9]+([_\.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+\.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
$errors[] = "E-mail is not in name#domain format!";
}
if(!$first || !$last || !$username || !$password || !$pass_conf || !$email || !$about)
{
$errors[] = "You did not fill out the required fields";
}
$sql = "SELECT * FROM `users` WHERE `username`='{$username}'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) == 1)
{
$errors[] = "Username already taken, please try another";
}
if(count($errors) > 0)
{
echo "The following errors occured with your registration";
echo "<font color=\"red\">";
foreach($errors AS $error)
{
echo "<p>" . $error . "\n";
}
echo "</font>";
echo "Try again";
//we use javascript to go back rather than reloading the page
// so the user doesn't have to type in all that info again.
}
else
{
$sql = "INSERT into `users`(`first`,`last`,`username`,`password`,`email`,`about`)
VALUES ('$first','$last','$username','".md5($password)."','$email','$about');";
$query = mysql_query($sql) or die(mysql_error());
echo "Thank You for registering {$first}! Your username is {$username}";
echo " Click here to Login";
}
}
?>
If there is no POST parameter at all or if there is no parameter named submit then you're trying to access an array index that does not exists, hence the warning. You can simply test if there is such an index/element in the _POST array.
if( isset($_POST['submit']) )
It doesn't check the value (like you original script, which tests if the value of _POST['submit'] equals false, see type juggling), but the mere existence of the index/element should suffice in this case.
see http://docs.php.net/isset
To get rid of this error, it should be:
if(!isset($_POST['submit']))
However, your code is already OK.
What you are getting is not an error, it is a warning, which is caused by having strict warnings enabld. PHP is a dynamic language which does not usually require to define variables and array keys, and most documentation and code will skip this part. So you should consider turning this feature off, as it clutters code and has few additional benefits. Or, switch to a statically compiled language (say asp.net) which will really benefit from defined variables and static typing.
Your $_POST does not exist when you first load your page. Change your check to something like:
if(!isset($_POST["submit"]))
Because you did not post anything yet, there will be no "submit" key in your $_POST array. That's what causes the warning.
For those posting use if(isset($_POST['submit'])), you clearly did not read his code. He has put is there is not a submit write the HTML form else use the fields (backwards righting to me!)
If he wants to keep the structure as is, it should be
if(empty($_POST['submit']))