This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I have created a simple form validation, the PHP code when used inside the value attribute to auto type the form, the name and he comments display properly expect the email (input type="text").Have I written the code correctly or has my code has any code smells.
Edit: My question is not that, I don't receive a main it is that
I get a value of 1 or the value gets cleared of.
PHP code :-
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$error="";
if(strlen ( $_POST['name'] ) < 5 ) {
$error = "Please type more than 4 characters<br/>";
}
if ( $_POST['email']="" || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) ){
$error.= "Please type a valid Email<br/>";
}
if(strlen($_POST['comment']) < 4){
$error.= "Please type more than 4 characters";
}
if( !empty($error) ){
$result = "<div class='alert alert-danger'>$error</div>";
}
else {
if( mail('jokersspirit#gmail.com','test message',"Name:".$_POST['name'].
"Email:".$_POST['email'].
"Comment:".$_POST['comment']) ){
$result = "<div class='alert alert-success'>Your form has been submitted</div>";
}
else{
$result = "<div class='alert alert-success'>Error occurred
while submitting your form please try again later</div>";
}
}
}
?>
HTML code : -
<form action="" method="post">
<label for="name">Your Name:</label>
<input type="text" class="form-control" name="name" id="name" placeholder="name" value="<?php echo isset($_POST['name'])?$_POST['name']:""; ?>">
<label for="email">Your Email:</label>
<input type="text" class="form-control" name="email" id="email" placeholder="email" value="<?php echo isset($_POST['email'])? $_POST['email']:""; ?>">
<label for="comment">Your Comments:</label>
<textarea name="comment" placeholder="comments" class="form-control" id="comment">
<?php echo isset($_POST['comment'])?$_POST['comment']:""; ?>
</textarea>
<input type="submit" class="btn btn-success btn-lg " value="Submit">
</form>
Your error is here
if ( $_POST['email']="" || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) ){
Replace it by :
if ( $_POST['email']=="" || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) ){
(= replaced by ==)
Without it, your $_POST['email'] is an empty string.
Related
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>';
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Goodday house,i'm developing this site that has a registration/login page as my first project and i'm stucked right now.
I added php validation to my registration form but the database insert statement refuses to work after,though all conditional statements were fulfilled,i tried putting a redirect loop immediately after the insert statement but my script automatically (somehow) jumps the "Insert statement" and processes the redirect code..
This is the code below
<!-- Php validation-->
<?php
include 'var.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Starts an array to store errors.
//Validation rules involves trimming,validating and sanitizating
$name = trim($_POST['name']);
$strippedname = mysqli_real_escape_string($con, strip_tags($name)) ;
$length = mb_strlen($strippedname, 'utf-8') ;
if ($length < 8 ) {
$errors[]= 'Your full name shouldn\'t be less than 8 letters' ;
} else {
$name = $strippedname ;
}
$email = FALSE ;
if (empty($_POST['email'])) {
$errors[] = 'You didn\'t provide any email address' ;
} // Next is removal of spaces and validation.
if (filter_var((trim($_POST['email'])), FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string($con, (trim($_POST['email'])));
}
else {
$errors[] = 'Email address was provided in the wrong format';
}
$pho = trim($_POST['phone']) ; // next line of code removes all characters that aren't digits
$phon = preg_replace('/\D+/', '', ($_POST['phone']));
$strippedphone = mysqli_real_escape_string($con, strip_tags($phon));
$length = mb_strlen($strippedphone, 'utf-8') ;
if ($length <> 11 ) {
$errors[] = 'Phone number should contain only eleven digits';
}
else {
$phone = $strippedphone ;
}
$add = trim($_POST['address']) ;
$strippedadd = mysqli_real_escape_string($con, strip_tags($add)) ;
$length = mb_strlen($strippedadd, 'utf-8') ;
if ($length < 15) {
$errors[]= 'Address should not be lesser than 15 letters' ;
} else {
$address = $strippedadd ;
}
if (empty($_POST['gender'])) {
$errors[] = 'You didn\'t select a gender';
} else {
$gend = trim($_POST['gender']);
}
$user = trim($_POST['username']);
$strippeduser = mysqli_real_escape_string($con, strip_tags($user)) ;
$length = mb_strlen($strippeduser, 'utf-8') ;
if ($length < 6) {
$errors[] = 'Username should contain a minimum of 6 letters and maximum of 18';
} else {
$confirmeduser = $strippeduser ;
}
if (empty($_POST['password'])){
$errors[] ='Please enter a valid password';
}
if(!preg_match('/^\w{10,40}$/', $_POST['password'])) {
$errors[] = 'Invalid password, use 10 to 40 characters without applying spacing.';
} else{
$password = $_POST['password'];
}
if($_POST['password'] == $_POST['confirm_password']) {
$pass = mysqli_real_escape_string($con, trim($password));
$newpass = password_hash($pass, PASSWORD_DEFAULT) ;
}else{
$errors[] = 'passwords don\'t match.';
}
if(empty($errors)) { // If no problems occurred
//Determine whether the email address has already been registered for a user
$query = mysqli_query($con, "INSERT INTO `customer`(`name`, `email`,
`phone`, `address`, `gender`, `username`, `password`) VALUES($name,$email,$phone,
$address,$gend,$confirmeduser,$newpass)") ;
echo "Done";
// end of mysqli_num_Rows
} // End of if (empty($errors))
else{ // Display the errors if any are found.
echo '
<p class="error">The following error(s) were found in the submitted form :<br>';
foreach ($errors as $msg) { // Echo each error
echo " $msg<br>";
}
}
}
?>
This is the html form
<form action="register.php" method="POST" class="form-horizontal" style="margin-top:30px" id="signup">
<fieldset> <div class="form-group">
<legend> Customer Details </legend>
</div>
<div class="form-group">
<label for="name" class="control-label"> Full Name : </label>
<input type="text" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"
name="name" placeholder="Your Full Name" class="required" title="Please type in your name" >
</div>
<div class="form-group">
<label for="email" class="control-label"> Email address </label>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"
placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="phone" class="control-label"> Phone Number :</label>
<input type="tel" name="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>"
placeholder="08137871320" class="required digits">
</div>
<div class="form-group">
<label for="address" class="control-label"> Contact Address : </label>
<input type="text" name="address" value="<?php if (isset($_POST['address'])) echo $_POST['address']; ?>"
placeholder="No 4,street name,ikeja"
class="required" title="Please type in contact address plus your city's name">
</div>
<!--<div class="form-group">
Drop down menu for selecting a state from the 36 states to be provided
</div>-->
<div class="form-group">
<label for="name">Select Your gender :</label>
<select name="gender" class="form-control">
<option value="male" > Male </option>
<option value="female">Female </option>
</select>
</div>
</fieldset>
<fieldset> <div class="form-group">
<legend> Login Information </legend>
</div>
<div class="form-group">
<label for="username" class="control-label"> Username : </label>
<input type="text" name="username" placeholder="e.g Lords" value="<?php if (isset($_POST['username']))
echo $_POST['username']; ?>">
</div>
<div class="form-group">
<label for="password" class="control-label"> Password : </label>
<input type="password" name="password" id="password" placeholder="Your Password Here">
</div>
<div class="form-group">
<label for="cpassword" class="control-label">Confirm Password : </label>
<input type="password" name="confirm_password" placeholder="Confirm Your Password Here">
</div>
</fieldset>
</div>
</div>
</div>
<div class="form-group" style="text-align:center">
<button type="submit" class="btn btn-success" name="submit"> REGISTER </button>
<button type="reset" id="fat-btn" class="btn btn-danger" data-loading-text="Loading..."> RESET </button> <br>
<p class="lead">
Already a registered user ?,do make use of the
<a href="login.php" class="navbar-link" data-toggle="tooltip" title="When clicked upon,
a page requesting for your username and password is generated,allowing you to book orders">
login page </a>
</p>
</div>
</form>
Thanks a lot for your reply
Since we're more than likely dealing with strings, these variables in your VALUES
($name,$email,$phone,$address,$gend,$confirmeduser,$newpass)
needs to be quoted:
('$name','$email','$phone','$address','$gend','$confirmeduser','$newpass')
Had you checked for errors using or die(mysqli_error($con)) to mysqli_query()
would have signaled the quotes errors.
Sidenote:
You should use prepared statements, or PDO with prepared statements, they're much safer.
Additional note that Barmar spotted:
<?phpinclude 'var.php';
there needs to be a space in there between php and include
<?php include 'var.php';
unless that's a copy/paste error or typo.
and >? again, another spotted error which should be ?>
On the PHP side of things:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input onclick="this.value=''" type="text" name="first_name" value="First Name">
<input onclick="this.value=''" type="text" name="last_name" value="Last Name">
<input onclick="this.value=''" type="text" name="pwd" value="The Passcode">
<input name="submit" type="submit" value="Submit" class="submit_">
<textarea name="comments" id="comments" rows="4" cols="50"></textarea>
</form>
PHP :
if(isset($_POST['submit']))
{
$name = mysql_real_escape_string($_POST['first_name']);
$pwd = mysql_real_escape_string($_POST['pwd']);
$text = mysql_real_escape_string($_POST['comments']);
// print_r($_POST);
if(is_null($text)) {
debug_to_console('some fields empty');
echo "<p class=\"warning\">* Your Message Did Not Contain Any Characters.</p>";
}
else if($name === 'First Name'){
debug_to_console('name isnt set');
echo "<p class=\"warning\">* You Have Not Entered Your First Name Correctly.</p>";
}
else if($pwd !== 'XyZ'){
debug_to_console('password not set');
echo "<p class=\"warning\">* Passcodes Do Not Match.</p>";
} else {
Keeps returning 'password not set' even though the form input matches the variable. Used print_r and $pwd states XyZ.
tried removing onClick from the form input. I'm assuming this is a caps thing?
Please help, thank you.
Check $pwd with
var_dump($pwd);
I do believe $pwd is a string (because you use !== instead of !=) AND doesn't contain: XyZ
(if you didn't change the value in input field pwd, its value is still: The Passcode)
This question already has an answer here:
How to validate form in php
(1 answer)
Closed 8 years ago.
Anyone please help me on how to validate a form? I have the code, it is working ok..but I found that after I hit the submit button & php shows the errors, there is an input field, asking the user to answer the math Ques..when I enter the answer, then hit submit button again, it just says mail successfully sent, but other fields are still empty. Any ideas how to fix it. Also, the php value in the answerbox input tags, is not saving the text in box, it disappears. by the way, I got some help from other users, i'm a noob in php, so if you don't mind please explain.
Thanks for your time!
<form name="contact" action="formtest.php" method="post">
<label for="YourName">Your Name:</label>
<input type="text" name="name" class="required" value="<?= isset($_POST['name']) ? $_POST['name'] : '' ?>" />
<label for="YourEmail">Your Email:</label>
<input type="text" name="email" class="required" value="<?= isset($_POST['email']) ? $_POST['email'] : '' ?>"/>
<label for="Subject">Subject:</label>
<input type="text" name="subject" class="required" value="<?= isset($_POST['subject']) ? $_POST['subject'] : '' ?>" />
<label for="YourMessage">Your Message:</label>
<textarea name="message" class="required"><?= isset($_POST['message']) ? $_POST['message'] : '' ?></textarea>
<p class="c3">10 + 5 =<input type="text" name="answerbox" id="answerbox" "<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send" class="required"/>
<input type="reset" id="reset" value="Reset"/>
</fieldset>
<?php
if(isset($_POST['submit'])){
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if(empty($_POST['name'])){
print "<div class='formerrors'><li>Please type your name.</li></div>";
}
else {
if (ctype_alpha($name) === false) {
print "<div class='formerrors'><li>Your name only should be in letters!</li></div>";
}
}
if(empty($_POST['email'])){
print "<div class='formerrors'><li>You've forgot to type your email address.</li></div>";
} else{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
print "<div class='formerrors'><li>Your email is not valid, please check.</li></div>";
}
}
if(empty($_POST['subject'])){
print "<div class='formerrors'><li>Please type a subject.</li></div>";
}
if(empty($_POST['message'])){
print "<div class='formerrors'><li>You've forgot to type your message.</li></div>";
}
if(empty($_POST['answerbox'])){
print "<div class='formerrors'><li>Please answer the math question.</li></div>";
}
else {
if($answerbox != 15){
print"<div class='formerrors'><li>Answer is not correct.</li></div>";
}
else{
$headers = 'From: '.$email. "\r\n" .
'Reply-To: '.$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('me#mymail.me',$subject,$message,$headers);
print "<div class='formerrors'><li>mail succesuffully sent</li></div>";
}
}
}
?>
</form>
Try placing your php code above the html as it is php setting the values of the variables, and you are calling them before they are set.
It is best practice to have php code at the top of the file, and then html below it, or even have the php on a separate file, but include it at the top.
Also I find it better to create an array of errors, and then if the array count is 0, then perform the action (send email) else call the error of arrays within the html, not the php. Then you can choose where to display it on the page, and style it accordingly.
Change your form action to
<?php $PHP_SELF; ?>
So it has to be
<form name="contact" action="<?php $PHP_SELF; ?>" method="post">
For the other issue you must place your code above the form.
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']))