Creating a Form Using HTML & PHP [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am trying to create a form on a website (http://youngliferaffle.com/) using HTML, PHP, and bootstrap twitter. I've been looking through several tutorials on how to create it but I think I'm having trouble with Locations -- as in relocating the user if they make an error or after they submit their answers. I'm also very new to PHP. I would really appreciate the help! Thank you!
Main issues:
"Too many redirects to the webpage"/possibly due to cookies
Not receiving an email from submissions
User not being redirected to the correct page after submission or due to bad submission
Here is the part of my HTML form:
<form method="POST" action="contact-form-submission.php">
<fieldset>
<label><strong>Sign-Up</strong></label>
<input type="text" class="name" name="cname" id="name" placeholder="Full Name"></input>
<input type="text" class="phone" name="phone" id="phone" placeholder="Phone Number"></input>
<input type="text" class="email" name="email" id="email" placeholder="Email Address"></input>
<div class="form-actions">
<input type="submit" name="save" value="Send">
</div>
</fieldset>
</form>
Here is my PHP form
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST['save']) || $_POST['save'] != 'contact') {
header('Location: contact-form-submission.php');
exit;
}
// get the posted data
$name = $_POST['contact_name'];
$email_address = $_POST['contact_email'];
$phone = $_POST['contact_phone'];
// check that a name was entered
if (empty($name))
$error = 'You must enter your name.';
// check that an email address was entered
elseif (empty($email_address))
$error = 'You must enter your email address.';
// check for a valid email address
elseif (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email_address))
$error = 'You must enter a valid email address.';
// check that a phone number was entered
elseif (empty($phone))
$error = 'You must enter a phone number.';
// check if an error was found - if there was, send the user back to the form
if (isset($error)) {
//Am I putting the wrong location?
header('Location: contact-form-submission.php?e='.urlencode($error)); exit;
}
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Phone:\n\n$phone";
// send the email
mail ("myemail.com", "New Contact Message", $email_content);
// send the user back to the form
//And This is where I'm having trouble with! the Location part
header('Location: contact-form-submission.phps='.urlencode('Thank you for your message.'));
exit;

the last line
header('Location: contact-form-submission.phps='.urlencode('Thank you for your message.')); exit;
seems like you have the name right. Why redirect the php file to itself. You should use the URL of the initial form, whatever name that is. Probably this line creates the redirect loop error you get.

Well the first thing in php code is that it redirects to itself. The 'save' variable won't be set anyway so it redirects again and again endlessly. It checks if 'save' is set, but it's not set the first time, so it redirects to the same page again. But 'save' variable won't be set again because it's just a redirect not a form submission. So it happens again and again so you get that too many redirects error.
I usually keep the processing logic and the form in the same PHP file. That means, the form's action attribute will have the same page URL as value. For example like this.
simple_form.php
<?php
//Assume the form has one field called field1 and a 'save' variable to indicate form submission
$field1 = "";
//Declare an array to store errors
$errors = array();
if(isset($_POST['save'])) {
//Form has been submitted.. do validations etc.
$field1 = $_POST['field1'];
if(someValidationCheck($field1) == false) {
$errors[] = "Field1 is not valid";
}
//After all field validations.. adding errors to $errors array..
if(count($errors) == 0) {
//No errors so write database insert statments etc. here
//Also put a header("Location:...") redirect here if you want to redirect to a thank you page etc.
}
}
?>
<html>
<body>
<?php
//If there were errors, show them here
if(count($errors) > 0) {
//loop through $errors array .. print one by one.
}
?>
<form method="post" action="simple_form.php">
<input type="text" name="field1" value="<?php echo($field1); ?>" />
<input type="hidden" name="save" value="save" />
<input type="submit" />
</form>
</body>
</html>
That way if there are errors, the user will see error messages in the same page, the fields will also retain their original values. And it'll get redirected only upon a valid submission with no errors. Otherwise it'll stay in the same page, displaying error messages.

In the very first line, you keep heading back to the same location. This creates a loop. You need to send them back to the form. Possibly index.php?
Also, the very last line, as this page will only work when data is being posted, you need to redirect users away from this page. Maybe make a new thankyou page.
Also remember your ? after .php as the ? tells your web server its no longer a file name. Else it will look for a file called thankyou.phps.
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST['save']) || $_POST['save'] != 'contact') {
header('Location: index.php'); exit;
}
// get the posted data
$name = $_POST['contact_name'];
$email_address = $_POST['contact_email'];
$phone = $_POST['contact_phone'];
// check that a name was entered
if (empty($name))
$error = 'You must enter your name.';
// check that an email address was entered
elseif (empty($email_address))
$error = 'You must enter your email address.';
// check for a valid email address
elseif (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email_address))
$error = 'You must enter a valid email address.';
// check that a phone number was entered
elseif (empty($phone))
$error = 'You must enter a phone number.';
// check if an error was found - if there was, send the user back to the form
if (isset($error)) {
//Am I putting the wrong location?
header('Location: contact-form-submission.php?e='.urlencode($error)); exit;
}
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Phone:\n\n$phone";
// send the email
mail ("myemail.com", "New Contact Message", $email_content);
// send the user back to the form
// remember the ? after your file name!
header('Location: thankyou.php?s='.urlencode('Thank you for your message.')); exit;

Related

CMS made simple - adding a php form

I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.

PHP mail() won't send when included in other PHP file with user input email

I am generating a page of information from a database. I need to send an email with the page content as a reminder. (example here takes input as message)
It takes in an email address and is supposed to send the details to that address.
<div class="container">
<?php
$name = $_GET['info'];
if(isset($name)){
$info = explode('|', $name);
/*****************************************************
open conection to the mySQL database
******************************************************/
....
/*****************************************************
Populate the page
******************************************************/
$sql="Select information from table";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
/*Title*/
echo '<h1>'.$row['post_title'].'</h1><hr>';
/*content*/
echo '<h2>Details: </h2><br>'.$row['post_content'].'<br>';
$content = $row['post_title'];
/*Reminder*/
echo '<div data-role="collapsible">
<h1>Send a reminder</h1>';
include("includes/email_reminder.php");
echo'</div>';
}
/*****************************************************
Close connection
******************************************************/
mysqli_close($con);
} else {
echo'Nothing selected. Go back <br>
<img src="img/icon/Back.png" style="height: 3em" > ';
}
?>
</div>
That creates a form at the bottom of the page to take in the email that needs that needs a reminder.
This is email_reminder.php:
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
?>
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
}
else // the user has submitted the form
{
// Check if the "from" input field is filled out
if (isset($_POST["to"]))
{
// Check if "from" email address is valid
$receivecheck = spamcheck($_POST["to"]);
if ($receivecheck==FALSE)
{
echo "Invalid input";
}
else
{
$to = $_POST["to"]; //receiver
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("$to",$subject,$message,"From: myaddress#mail.com\n");
echo "reminder has been sent";
}
}
}
?>
I have used that form in isolation (just opened email_reminder.php on its own) and it sent emails correctly from whichever email address I used. It just doesn't send when included in the other script.
include(emai_reminder.php); needs single quotes surrounding the file name (and email correctly spelled: include('email_reminder.php');
But, it looks like you need more help than just this. For example, there is no field FROM in your form, although you reference $_POST["from"]. You're running validation against that variable, which doesn't exist, which fails validation, which prevents the else if block from running, which prevents mail() from ever being called.
Several reasons why mailing to different user-defined addresses may not work:
1.) Check the result from the mail() call is TRUE, just to make sure the underlying sendmail (if you are on Linux) did not return an error.
2.) Add additional headers to prevent problems when delivering mails to foreign SMTP hosts, an example may be found on PHP doc for mail()
3.) In some cases (i.e. when using SMTP on Windows) using the PEAR Mail package may solve your problem. It also supports ASMTP and error trapping is much easier compared to the mail() function.

Validating form and sending a confirmation email on submission

I am creating an admin page, where the admin person can create users accounts for people. The idea is, that once the form is completed, when clicking 'Submit' an email must be sent to the user (containing the ID and name of account selected). In the same action, the form must also first be validated and if there are any errors with the validation the data should not be submitted to the database. None of this is happening though and I cannot figure out why.
The email is not being sent,
the data is inserted in the database even if there are errors and upon loading the page,
errors are displayed for all form fields even though the submit button have not been clicked.
Any help, advice or links to possible sources/tutorials would be greatly appreciated.
Below is my code: (Note that I am only working in PHP, HTML and using a MYSQL database)
<html>
<head>
<title>
User Registration
</title>
<?PHP
include_once 'includes\functions.php';
connect();
error_reporting(E_ERROR | E_PARSE);
//Assign variables
$accounttype=mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
//Validating form(part1)
$error='';
//Connect to database
$SQL=
"INSERT INTO student
(
sname,fname,email, address, contact_flag
)
VALUES
(
'$sname', '$fname', '$email', '$address', '$contact_flag'
)
";
if (!mysql_query($SQL))
{
print'Error: '.mysql_error();
}
mysql_close($db_handle);
//Validate form(part 2)
if (isset($_POST['sname'], $_POST['fname'],$_POST['email'],$_POST['address']));
{
$errors=array();
$accounttype= mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
// form validation
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
{
$errors[]='Please insert your valid email address';
}
if(strlen(mysql_real_escape_string($address))<8)
{
$errors[]='Please insert your postal address';
}
echo'<pre>';
print_r($errors);
echo'</pre>';
}
//confirmation email
// Subject of confirmation email.
$conf_subject = 'Registration confirmed';
// Who should the confirmation email be from?
$conf_sender = 'PHP Project <my#email.com>';
$msg = $_POST['fname'] . ",\n\nThank you for registering. \n\n You registered for account:".$accounttype."\n\n Your account number:".mysql_insert_id;
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
?>
</head>
<body>
</br>
<form name ="form0" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<b>Select the course you wish to register for:</b></br>
<select name="accounttype">
<?PHP query() ?>
</select>
<?PHP close() ?>
</form>
<form name ="form1" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<Input type ="" Value = "Surname" Name = "sname"></br>
<Input type ="" Value = "First name" Name = "fname"></br>
<b>Email:</b> <Input type ="" Value = "" Name = "email"></br>
<b>Address:</b> </br>
<textarea rows="4" cols="20" Name="address">Please provide your postal address here </textarea></br>
<b>Tick to receive confinmation email:</b> <Input type ="checkbox" Value = "1" Name = "contact_flag"></br>
<Input type = "Submit" Value="Submit">
</form>
</body>
</html>
<?PHP
if(isset($_POST['submit']))
{
include_once 'includes\functions.php';
connect();
// your rest of the code
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
}
?>
and keep this code out of the <html> tag but before it
and if you want to stick to PHP only then one error i can see is
that you have kept the **validation code below the `INSERT`**
query which means that the insert query will be executed first which will store the data in the database first and then it will go for the validation...so keep your validation code above the INSERT statement..
and second thing use exit() method after vaidating every field if it gives you error...it will stop executing rest of the php code if any field gives the error during validation....and so it will also prevent the data from storing into the database if it finds exit method whenever an error is found eg
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
echo '//whatever you want to echo';
exit();
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
echo '//whatever you want to echo';
exit();
}
At first, your query gets executed before you validate your form.
Move your SQL after your
echo'<pre>';
print_r($errors);
echo'</pre>';
and surround it with
if(!$errors){}
This will prevent your query from being executed if there are any errors.
(You can also delete your first assignement of your variables)
Concerning your email problem, test your connection with a simple message
mail('your#email.com', 'subject', 'message');
If you get any error, probably your mailserver isn't set up right

validate email address – check if empty

After spending hours I still cant figure it out. I'm trying to validate an email address but every time and no matter what Ii type it gives me the message as if it was empty "You did not enter an email address!".
Edit: Fixed invalid email address error because I did not add a name to my input text. Now when I enter a correct email, it keeps loading "please wait". Any ideas? Is it because its not connecting to mysql?
$email = mysql_real_escape_string($_POST['signup-email']);
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA- Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
HTML:
<div id="signupform">
<form id="newsletter-signup" action="?action=signup" method="post">
<fieldset>
<input type="text" name="signup-email" id="signup-email" size="20" value="Email Address" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
<input type="submit" id="signup-button" value="+"/>
</br></br><p id="signup-response"></p>
</fieldset>
</form>
if(strlen($_POST['signup-email'])) == 0){
$status = "error";
$message = "You did not enter an email address!";
}
and then give your post variable a name:
<input type="text" name='signup-email' id="signup-email" size="20" value="Email Address" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
You don't have a field named email in your form...
Also you should do: if(!isset($_POST['email'])) {
If I understand you correctly (unless you haven't posted all code).
Try adding name="email" to the email input's html... Also, $email should be defined something like $email = $_POST['email'];
Your input fields do not have names, PHP retrieves $_POST variables from the name attribute of the input. So in other words, no name, no access to that input's value.
Take draevor's advice and add the name attribute to your inputs.
Also you have a large amount of spaces in your regex between [a-zA- and Z0-9_]
'/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA- Z0-9_]+)*\.[a-zA-Z]{2,4}$/'
Not sure if that's from copying and pasting, but if those spaces are in your source code it may cause the regex not to work. I've never heard of an "ignore whitespace" flag for the preg_match() function, correct me if I'm wrong.

How would I go about making this error message appear when form field is not right?

I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:
if(isset($_POST['submit'])) {
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
$error = "";
} else {
$error = "Please fill in the required fields.";
}
}
In the form, I have a span class like so:
<span class="error">'.$error.'</span>
I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?
Thanks so much for any help or tips!
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script. You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.
Are you echoing out the error message within the span, or is all that output being placed after an echo statement?
echo '<span class="error">'.$error.'</span>'
Or, if not in the PHP context outside of script
<span class="error"><? echo $error; ?></span>
Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.
You don't need any AJAX.
$error = '';
if (isset($_POST['submit'])) {
if ( <<< insert check for required fields >>> ) {
// handle form, send mail, etc
// you may want to redirect on success to prevent double posting
} else {
$error = "Please fill in the required fields.";
}
}
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.
<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
} else {
$error = "Please fill in the required fields.";
}
}else{ ?>
<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
<span class="error><?php echo $error; ?></span>
Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
<input type="submit" value="Submit Email"/>
</form></div>
<?php } ?>
When I handle form validations, I tend to create an array to hold the error messages, like so:
<?php
$error = array();
if( $POST ){
# Form is Submitted
if( /* TRUE if "email" is empty */ ){
$error['email'] = 'Please provide an Email Address';
}elseif( /* TRUE if "email" is not a valid address */ ){
$error['email'] = 'Please provide a Valid Email Address';
}elseif( /* TRUE if "email" is already associated with a User */ ){
$error['email'] = 'The Provided Email Address is Already Taken';
}
...
if( count( $error )==0 ){
# No Error has been Recorded
# Do Successful Things
}
} /* Closing if( $_POST ){ */
Then within the presentation/display section, I have something like:
<?php if( count( $error )>0 ){ ?>
<div id="error">
The following Errors have occurred:
<ul>
<?php foreach( $error as $k => $v ){ ?>
<li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
And within the form, something like:
<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
This means that:
Customised, multi-tiered error messages can be recorded.
A summary of the error messages can be shown.
Fields associated with the error messages can be marked.
Has worked well in my experience thusfar.
Yep, I think You have two methods to do that, as already explained above...
When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...
You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..
What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)
Thank You.
ADynaMic
My suggest is to use ajax call when submit,
according to the answer come back, you update the span of error.
you can find a lot of examples in web like
http://jqueryfordesigners.com/using-ajax-to-validate-forms/
http://www.the-art-of-web.com/javascript/ajax-validate/

Categories