I have been trying to improve our contact forms with php validation, I can get the form to be validated and show errors when each field is not filled in correctly, success message appears when the form is completed and validated correctly, and an email is sent to me with the information from the form.
My problem is that I can not get the header('location'...) part of the code to work. Rather than just having "Form has been submitted successfully" appear underneath the form once submitted, I would like it to go to a "Thank You" page instead.
Here is my code:
This is this my form page:
<?php
include('validate.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<style>
input, textarea {font-size: 1em;}
p.error {background: #ffd; color: red;}
p.error:before {content: "Error:";}
p.success {background: #ffd; color: green;}
p.success:before {content: "Success:";}
p.error, p.success {font-weight: bold;}
</style>
</head>
<body>
<h2>Please fill up the form below and submit.</h2>
<?=$error?>
<form action="html_form_to_validate.php" method="post">
<table>
<tr>
<td>Name: </td>
<td>
<input type="text" name="name" placeholder="Name *(Required)" value="<?=#$name?>"/> </td>
</tr>
<tr>
<td>Company: </td>
<td><input type="text" name="company" placeholder="Company" value="<?=#$company?>"/> </td>
</tr>
<tr>
<td>Hear: </td>
<td><input type="text" name="hear" placeholder="How did you hear about us?" value="<?=#$hear?>"/></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email" value="<?=#$email?>"/></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone" value="<?=#$phone?>"/></td>
</tr>
<tr>
<td>Message: </td>
<td><textarea name="comments"><?=#$comments?></textarea></td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/> <input type="reset" name="reset" value="Reset"/>
</form>
<?php
if (isset($_POST['submit']) && $error == '') { // if there is no error, then process further
echo "<p class='success'>Form has been submitted successfully.</p>"; // showing success message
$name=$_POST['name'];
$company=$_POST['company'];
$telephone=$_POST['telephone'];
$email=$_POST['email'];
$hear=$_POST['hear'];
$comments=$_POST['comments'];
$to="chris#example.com";
$subject="Request for information";
$from="sales#example.com";
$message="<html>
<body topmargin='0'>
<div align='center'>
<table border='0' width='736' id='table1' cellspacing='0' cellpadding='0'>
<tr>
<td height='129' bgcolor='#EDEDE9' width='736' valign='top' style='margin-left: 10'>
<table border='0' id='table2' cellspacing='10' cellpadding='15' width='726'>
<tr>
<td width='676' valign='top' bgcolor='#FFFFFF'>
<p align='left'>
<img border='0' src='http://www.example.com/images/logo.png' align='left' hspace='0'> </p>
<p align='left'>
<br><br>
<b>
<font face='Verdana' color='#0078c1' style='font-size: 20pt'>
Request for information</font></b></p>
<p align='left'> </p>
</td>
</tr>
<tr>
<td width='676' valign='top' bgcolor='#FFFFFF'>
<p>
<font face='Verdana' size='2'>The following person has been on <a href='http://www.example.com'>
<font color='#0078c1'>www.example.com</font></a> and requesting information from our 'contact form'.</font></p>
<p>
<font face='Verdana' size='2'>Name: </font><font face='Verdana' size='2'><b>$name</b> </font></p>
<p>
<font face='Verdana' size='2'>Company: </font><font face='Verdana' size='2'><b>$company</b></font></p>
<p>
<font face='Verdana' size='2'>Telephone: <font face='Verdana' size='2'><b>$telephone</b></font></p>
<p>
<font face='Verdana' size='2'>Email: <font face='Verdana' size='2'><b>$email</b></font></p>
<p>
<font face='Verdana' size='2'>Heard about us from: </font><font face='Verdana' size='2'><b>$hear</b></font></p>
<p>
<font face='Verdana' size='2'>Message: <font face='Verdana' size='2'><b>$comments</b></font></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: $from\r\n";
#mail($to, $subject, $message, $headers);
header('Location: http://www.example.com/contact/thank-you.php');
}
?>
</body>
</html>
And my validate.php file:
<?php
$error = ""; // Initialize error as blank
if (isset($_POST['submit'])) { // check if the form is submitted
#### removing extra white spaces & escaping harmful characters ####
$name = trim($_POST['name']);
$company = trim($_POST['company']);
$hear = trim($_POST['hear']);
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
#### start validating input data ####
#####################################
# Validate Name #
// if name is not 3-20 characters long, throw error
if (strlen($name) < 3 OR strlen($name) > 20) {
$error .= '<p class="error">Name should be within 3-20 characters long.</p>';
}
# Validate Email #
// if email is invalid, throw error
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // you can also use regex to do same
$error .= '<p class="error">Enter a valid email address.</p>';
}
# Validate Phone #
// if phone is invalid, throw error
if (!ctype_digit($phone) OR strlen($phone) < 9) {
$error .= '<p class="error">Enter a valid telephone number.</p>';
}
# Validate Comments #
if (strlen($comments)==0 OR strlen($comments)>240) {
$error .= '<p class="error">Please enter your message less than 240 characters.</p>';
}
#### end validating input data ####
#####################################
}
I am a novice and have used scripts from other places to do what I wanted to do - so be nice lol
Thanks
Chris
I personally love this method...
echo '<meta http-equiv="refresh" content="0;URL=www.mylink.com" />';
In my PHP code I always use header("refresh:0;url=the_url_here"); instead of header('Location: url');.
Try it, maybe it works to you.
Validation and redirect needs to happen before any output to the browser, so you need to place header function before showing form.
Or if you must do redirect after form you can use javascript redirect instead of PHP.
<script>
// just redirect
window.location='http://your-site.dev/new-url.php'
// or redirect after showing form
setTimeout(function () {
window.location.href = 'http://your-site.dev/new-url.php';
}, 2000); //will call the function after 2 secs.
</script>
I have a web form where the user is required to enter information for the following fields: Full Name, Contact Number and Best Time to Call. Once these fields have been filled the user will submit the form and the data is then added to the database however, my issue right now is that my web form is ignoring the validation i have set and allowing the user to submit a blank web form. I am not sure if it may be the way i have structured my code? nevertheless, how can i resolve this?
PHP
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/inc/bootstrap.php');
include("config/cn.php");
$template['template']="page";
// define variables and set to empty values
$nameErr = $contactErr = $callErrErr = "";
$full_name = $contact_number = $best_time_to_call = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["full_name"]))
{$nameErr = "Full name is required";}
else
{$full_name = test_input($_POST["full_name"]);}
if (empty($_POST["contact_number"]))
{$contactErr = "Contact number is required";}
else
{$contact_number = test_input($_POST["contact_number"]);}
if (empty($_POST["best_time_to_call"]))
{$callErr = "Must not be left blank";}
else
{$best_time_to_call = test_input($_POST["best_time_to_call"]);}
$enter_sql = "INSERT INTO contact (full_name,contact_number,best_time_to_call) VALUES('$full_name','$contact_number','$best_time_to_call')";
/*print($enter_sql);*/
$enter_query = mysql_query($enter_sql) or die(mysql_error());
header('Location: /thankyou.php');
exit;
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML
<form name="frmContact" id="frmCallContact" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="100%" border="0" cellspacing="1" cellpadding="0" class="TableFormat">
<tr><th align="left" valign="top" colspan="2">Call me back</th></tr>
<tr><td align="right" valign="top">Full Name:</td>
<td><input type="text" name="full_name" id="full_name" style="width:250px;" title="Please enter your full name"/><span class="error">* <?php echo $nameErr;?></span></td></tr>
<tr>
<td align="right" valign="top">Contact Number:</td>
<td><input type="text" name="contact_number" id="contact_number" style="width:250px;" />
<span class="error">*<?php echo $contactErr;?></span></td>
</tr>
<tr>
<td align="right" valign="top">Best Time to Call:</td>
<td><input type="text" name="best_time_to_call" id="best_time_to_call" style="width:250px;" title="Please enter your best time to call"/>
<span class="error">*<?php echo $callErr;?></span></td>
</tr>
<tr>
<td align="right" valign="top"> </td>
<td><!--<a name="submit" href="#"><img src="/img/bn_submit.png" width="93" height="28" /></a>--><input type="submit" name="Submit" value="Submit">
</tr>
</table>
</form>
$myflag = true; //create a flag
1.
if (empty($_POST["full_name"]))
{
echo $nameErr = "Full name is required"; // echo the error
$myflag = false; //change status of flag
}
2.
if ( $myflag )
{
//if flag is true then insert data;
$enter_sql = "INSERT INTO contact (full_name,contact_number,best_time_to_call) VALUES('$full_name','$contact_number','$best_time_to_call')";
}
3.you are vulnerable to SQL injection if the data is directly inserted into database from a user
I'm trying to create a form that will create a user in my database, so they can have a profile page. I'd also like the form to send an email to confirm activation. Where is my form disconnecting? As of right now, I'm not logging any content in my db and no email is being sent.
<?php include ("session.php"); ?>
<?php // Set error message as blank upon arrival to page
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['username'])){
//Connect to the database through our include
include_once "connect_to_mysql.php";
// Filter the posted variables
$username = ereg_replace("[^A-Za-z0-9]", "", $_POST['username']); // filter everything but numbers and letters
$address = ereg_replace("[^A-Z a-z0-9]", "", $_POST['address']); // filter everything but spaces, numbers, and letters
$city = ereg_replace("[^A-Z a-z0-9]", "", $_POST['state']); // filter everything but spaces, numbers, and letters
$state = ereg_replace("[^A-Z a-z0-9]", "", $_POST['city']); // filter everything but spaces, numbers, and letters
$accounttype = ereg_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters
$zip = ereg_replace("[^a-z]", "", $_POST['zip']); // filter everything but lowercase letters
$name = ereg_replace("[^A-Z a-z0-9]", "", $_POST['name']); // filter everything but spaces, numbers, and letters
$fax = ereg_replace("[^A-Z a-z0-9]", "", $_POST['fax']); // filter everything but spaces, numbers, and letters
$company = ereg_replace("[^A-Z a-z0-9]", "", $_POST['company']); // filter everything but spaces, numbers, and letters
$website = ereg_replace("[^A-Z a-z0-9]", "", $_POST['website']); // filter everything but spaces, numbers, and letters
$numemployees = ereg_replace("[^A-Z a-z0-9]", "", $_POST['numemployees']); // filter everything but spaces, numbers, and letters
$yearsbusiness = ereg_replace("[^A-Z a-z0-9]", "", $_POST['yearsbusiness']); // filter everything but spaces, numbers, and letters
$annualrevenue = ereg_replace("[^A-Z a-z0-9]", "", $_POST['annualrevenue']); // filter everything but spaces, numbers, and letters
$industrysector = ereg_replace("[^A-Z a-z0-9]", "", $_POST['industrysector']); // filter everything but spaces, numbers, and letters
$preferredcontact = ereg_replace("[^A-Z a-z0-9]", "", $_POST['preferredcontact']); // filter everything but spaces, numbers, and letters
$referralsource = ereg_replace("[^A-Z a-z0-9]", "", $_POST['referralsource']); // filter everything but spaces, numbers, and letters
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$username) || (!$address) || (!$state) || (!$city) || (!$accounttype) || (!$email) || (!$password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$username){
$errorMsg .= "--- User Name";
} else if(!$name){
$errorMsg .= "Please Enter Your Full Name.";
} else if(!$phone){
$errorMsg .= "Please enter your Phone Number.";
} else if(!$fax){
$errorMsg .= "Please enter your Fax Number.";
} else if(!$email){
$errorMsg .= "Please enter your Email Address.";
} else if(!$address){
$errorMsg .= "Please enter your Address.";
} else if(!$city){
$errorMsg .= "Please enter the City in which you reside";
} else if(!$state){
$errorMsg .= "Please enter the State in which you reside.";
} else if(!$zip){
$errorMsg .= "Please enter the Zip Code in which you reside";
} else if(!$company){
$errorMsg .= "Please enter the name f your Company.";
} else if(!$website){
$errorMsg .= "Please enter your company website.";
} else if(!$numemployees){
$errorMsg .= "Please enter the current number of employees at your company.";
} else if(!$yearsbusiness){
$errorMsg .= "Please enter the number of years you've been in business.";
} else if(!$annualrevenue){
$errorMsg .= "Please enter your companies Approximate Annual Revenue.";
} else if(!$industrysector){
$errorMsg .= "Please enter the Industry Sector.";
} else if(!$accounttype){
$errorMsg .= "Please choose a Membership Type.";
} else if(!$preferredcontact){
$errorMsg .= "Please enter your preferred method of contact.";
} else if(!$referralsource){
$errorMsg .= "Please enter the Referral Source.";
} else
// Database duplicate Fields Check
$sql_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$sql_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$username_check = mysql_num_rows($sql_username_check);
$email_check = mysql_num_rows($sql_email_check);
if ($username_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside our system. Please try another.";
} else if ($email_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
} else {
// Add MD5 Hash to the password variable
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, email, password, phone, address, city, state, zip, emailactivated, accounttype, lastlogin, signupdate, name, fax, company, website, numemployees, yearsbusiness, annualrevenue, industrysector, preferredcontact, referralsource)
VALUES('$username', '$email', '$password', '$phone', '$address', '$city', '$state', '$zip', '$emailactivated', '$accounttype', '$lastlogin', '$signupdate', '$name', '$fax', '$company', '$website', '$numemployees', '$yearsbusiness', '$annualrevenue', '$industrysector', '$preferredcontact', '$referralsource', now())") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
// Create directory(folder) to hold each user files(pics, MP3s, etc.)
mkdir("memberFiles/$id", 0755);
// Start assembly of Email Member the activation link
$to = "$email";
// Change this to your site admin email
$from = "###############";
$subject = "One Last Step";
//Begin HTML Email Message where you need to change the activation URL inside
$message = '<html>
<body bgcolor="#FFFFFF">
Hi ' . $name . ',
<br /><br />
One Last Step before we can review your application.
<br /><br />
Please click here to activate now >>
<a href="http://www.############.com/activation.php?id=' . $id . '">
ACTIVATE NOW</a>
<br /><br />
Your Login Data is as follows:
<br /><br />
E-mail Address: ' . $email . ' <br />
Password: ' . $password . '
<br /><br />
Thanks!
<br /><br />
Houstonians For A Better Tomorrow
</body>
</html>';
// end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";
// Finally send the activation email to the member
mail($to, $subject, $message, $headers);
// Then print a message to the browser for the joiner
print "<br /><br /><br /><h4>OK $firstname, one last step to verify your email identity:</h4><br />
We just sent an Activation link to: $email<br /><br />
<strong><font color=\"#990000\">Please check your email inbox in a moment</font></strong> to click on the Activation <br />
Link inside the message. After email activation you can log in.";
exit(); // Exit so the form and page does not display, just this success message
} // Close else after database duplicate field value checks
} // Close else after missing vars check
} //Close if $_POST
?>
<?php include ("header.php"); ?>
</div>
</div>
<?php include ("subhead.php"); ?>
<!-- Content Wrapper -->
<div class="contentWrapper">
<div class="outerShadow">
</div>
<div class="innerShadow">
</div>
<div class="center clearfix">
<!-- Additional clearfix necessary for non floated objects -->
<div class="clearfix">
</div>
<!-- Content Starts - Header template should end here -->
<!--Left layout column -->
<div class="siteColumnLeft">
<div class="column">
<table width="750" align="center" cellpadding="4">
<tr>
<td width="7%">Please complete the entire application. </td>
</tr>
</table>
<table width="600" align="center" cellpadding="5">
<form action="join_form.php" method="post" enctype="multipart/form-data">
<tr>
<td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
</tr>
<tr>
<td width="300"><div align="right">User Name:</div></td>
<td width="450"><input name="username" type="text" value="<?php echo "$username"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right"> Password: </div></td>
<td width="450"><input name="password" type="password" value="<?php echo "$password"; ?>" />
<font size="-2" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
</tr>
<tr>
<td width="300"><div align="right">Name:</div></td>
<td width="450"><input name="name" type="text" value="<?php echo "$name"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Phone:</div></td>
<td width="450"><input name="phone" type="text" value="<?php echo "$phone"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Fax:</div></td>
<td width="450"><input name="fax" type="text" value="<?php echo "$fax"; ?>" /></td>
</tr>
<tr>
<td width="163"><div align="right">Email:</div></td>
<td width="450"><input name="email" type="text" value="<?php echo "$email"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Address:</div></td>
<td width="450"><input name="address" type="text" value="<?php echo "$address"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">City: </div></td>
<td width="450"><input name="city" type="text" value="<?php echo "$city"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">State: </div></td>
<td width="450"><input name="state" type="text" value="<?php echo "$state"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Zip Code: </div></td>
<td width="450"><input name="zip" type="text" value="<?php echo "$zip"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Company: </div></td>
<td width="450"><input name="company" type="text" value="<?php echo "$company"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Website: </div></td>
<td width="450"><input name="website" type="text" value="<?php echo "$website"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">No. Of Employees: </div></td>
<td width="450"><input name="numemployees" type="text" value="<?php echo "$numemployees"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">How many years have you been in business? </div></td>
<td width="450"><input name="yearsbusiness" type="text" value="<?php echo "$yearsbusiness"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">What are your Approximate Annual Revenues? </div></td>
<td width="450"><input name="annualrevenue" type="text" value="<?php echo "$annualrevenue"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">Industry Sector: </div></td>
<td width="450"><input name="industrysector" type="text" value="<?php echo "$industrysector"; ?>" /></td>
</tr>
<tr>
<td width="300"><div align="right">What level would you like to become a member of Houstonians For A Better Tomorrow? </div></td>
<td width="450"><select name="accounttype">
<option value="<?php echo "$accounttype"; ?>"><?php echo "$accounttype"; ?></option>
<option value="a">Urban Small Business Member</option>
<option value="b">Corporate Member</option>
<option value="c">Non-Profit</option>
</select></td>
</tr>
<tr>
<td width="300"><div align="right">How do you prefer to receive updates? </div></td>
<td width="450"><select name="preferredcontact">
<option value="<?php echo "$preferredcontact"; ?>"><?php echo "$preferredcontact"; ?></option>
<option value="a">Email</option>
<option value="b">Fax</option>
<option value="c">Direct Mail</option>
</select></td>
</tr>
<tr>
<td width="300"><div align="right">How did you find out about Houstonians For A Better Tomorrow?</div></td>
<td width="450"><select name="referralsource">
<option value="<?php echo "$referralsource"; ?>"><?php echo "$referralsource"; ?></option>
<option value="a">Advertising - TV </option>
<option value="b">Advertising - Radio</option>
<option value="c">Advertising - Online</option>
<option value="c">Advertising - Print</option>
<option value="c">Referral</option>
</select></td>
</tr>
<tr>
<td width="300"><div align="right"></div></td>
<td width="450"><input type="submit" name="Submit" value="Submit Form" /></td>
</tr>
</form>
</table>
</div></div>
</div>
</div>
<!-- Twitter Widget -->
<div class="twitterWidget">
<div class="center">
<!-- Simply change the href to your username -->
<a class="profileLink" href="http://twitter.com/##############"></a><p>Loading<span>Retrieving latest tweet...</span></p>
</div>
</div>
<?php include ("footer.php"); ?>
</body></html>
Presuming join_form.php is the current form (use $_SERVER['PHP_SELF'] instead)...
Insert some debugging code so you can follow what is happening: at the top of the document put the following so you can see what is being passes.
var_dump($_POST);
After each `if' statement echo "Here 1" or "Here 2" so you can see where the code is going.
After your ereg_replace() use:
var_dump($username, $address, $state, $city, $accounttype, $email, $password);
Then you can start to debug your problem.
I'm working on a very simple, very easy contact form and when i did it on a separate page it worked perfectly, but when i added it to the current website it can't get the $_POST i don't know why. here are the codes
$to ="enter email here";
$name = $_POST["name"];
$email = $_POST["email"];
$header = "From " . $name;
$message = $_POST["message"];
$content = "From: ". $name ."<br /> Email: " . $email ."<br /> Message: " . $message;
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "illegal email";
}
else
{
if (!empty($name) && !empty($message)){
mail($to, $header, $content);
echo"sent <br />";
echo $content;
}else
{
if(empty($email))
{
echo "your email is empty";
}
elseif(empty($name))
{
echo "please enter your name";
}
elseif(empty($message)){
echo "can't send empty messages";
}
}
}
html
<form method="post" action="mail.php">
<table>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<input type="text" name="email"/>
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
<input type="text" name="subject"/>
</td>
</tr>
<tr>
<td>
Message: <br /><br/><br/>
</td>
<td>
<textarea style="resize:vertical;" name="message"></textarea>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit"/>
</td>
</tr>
</table>
</form>
thanks in advance and sorry if its a repeat
Check that the PHP is actually executing by adding something like this to the top:
echo "Testing PHP...";
If you do not see that output after submitting a form, check that you are posting the form to the right file. For example, you might need to use:
<form method="post" action="/mail.php">
or
<form method="post" action="/php/mail.php">
...code depending on your website structure.
It's certainly not $_POST that's broken, so it must be something either server related or an error in your code.
Do you have any other PHP on the website your importing the form to? If so you need to make sure that it isn't affecting it in any way.
One more thing to check, it has been reported that a PHP update accidently changed the upload limit size from "8M" to "10MB". Have a scan through your php.ini file and make sure that their isn't any unwanted "MB" instead of "M" in your upload limit.
One final suggestion I can give if you still haven't found the cause after this, is try using:
<?php var_dump($_POST); ?>
which should reveal what's really there.
PHP contact form phone validation of the correct amount of numbers
Hello,
I have this php form that validates the content once submitted a sticky php form is what it is called. It keeps the users data in the input box when an error if found so the user dose not have to re-enter all the data again.
When the phone number is submitted I need it to validate that there are 3 characters/numbers in the first input box then 3 in the next then 4 in the last one.
The way it is now as long as you input numbers in the first input box it over looks the rest of the input boxes for the phone number. So I am looking to add a minimum character/number script in the validation process. I have the form validating that it is a number at this time. I also need it to validate that there is the correct amount of numbers in each input box for the phone as well. I believe this is just changing the elseif statements to just if inside another if but that did not work either. Any help would be very appreciated. The Art Institute only taught so much with PHP, and not this.
This is the particular area of the script that validates the phone number:
//validate the phone number
if(is_numeric($_POST['phone01'])) {
$phone = $_POST['phone01']. '-';
}elseif(is_numeric($_POST['phone02'])) {
$phone .= $_POST['phone02']. '-';
}elseif(is_numeric($_POST['phone03'])) {
$phone .= $_POST['phone03'];
}else{
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
This is a copy of the whole script for the form itself:
<?php
// This page receives the data from itself and validates as well
//error reporting!
ini_set ('display_errors', 1);
//Shows all possible problem!
error_reporting (E_ALL);
// validate email
function isValidEmail($email){
return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
}
//show form
function show_form($firstName='',$lastName='',$businessName='',$email='',$phone01='',$phone02='',$phone03='',$message=''){
?>
<!--The form starts here -->
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact form" target="_self" id="contact form" dir="ltr" >
<table bgcolor="#000000" width="525" border="0" align="center">
<tr>
<td width="25%" align="right">*First Name:</td>
<td colspan="2" align="left"><input name="firstName" type="text" id="firstName" tabindex="1" size="30" value="<?php if(isset($_POST['firstName'])) { print htmlspecialchars($_POST['firstName']); }?>"/></td>
</tr>
<tr>
<td align="right">*Last Name:</td>
<td colspan="2" align="left"><input name="lastName" type="text" id="lastName" tabindex="2" size="30" value="<?php if(isset($_POST['lastName'])) {print htmlspecialchars($_POST['lastName']); }?>"/></td>
</tr>
<tr>
<td align="right">Business Name:</td>
<td colspan="2" align="left"><input name="businessName" type="text" id="businessName" tabindex="3" size="35" value="<?php if(isset($_POST['businessName'])) {print htmlspecialchars($_POST['businessName']); }?>"/></td>
</tr>
<tr>
<td align="right">*Email: </td>
<td colspan="2" align="left"><input name="email" type="text" id="email" tabindex="4" size="35" value="<?php if(isset($_POST['email'])) {print htmlspecialchars($_POST['email']); }?>"/></td>
</tr>
<tr>
<td align="right">*Phone Number:</td>
<td colspan="2" align="left">
<input name="phone01" type="text" id="phone01" size="3" maxlength="3" tabindex="5"value="<?php if(isset($_POST['phone01'])) {print htmlspecialchars($_POST['phone01']); }?>"/>
- <input name="phone02" type="text" id="phone02" size="3" maxlength="3" tabindex="6"value="<?php if(isset($_POST['phone02'])) {print htmlspecialchars($_POST['phone02']); }?>"/>
- <input name="phone03" type="text" id="phone03" size="4" maxlength="4" tabindex="7" value="<?php if(isset($_POST['phone03'])) {print htmlspecialchars($_POST['phone03']); }?>"/></td>
</tr>
<tr align="center">
<td align="right">*Message:</td>
<td colspan="2" align="left"><textarea name="message" type="text" id="message" tabindex="8" cols="45" rows="4"><?php if(isset($_POST['message'])) {print htmlspecialchars($_POST['message']); }?></textarea>
</td>
</tr>
<tr align="center">
<td> </td>
<td><input name="submit" type="submit" tabindex="9" value="Email" /></td>
<td><input type="reset" name="reset" id="reset" value=" Reset " tabindex="10"/></td>
</tr>
</table>
</form>
<?php
} // end of show_form function
$validate = TRUE;
if($_SERVER['REQUEST_METHOD']!='POST') {
show_form();
} else {
//validate form fields
//validate the first name
if(empty($_POST['firstName'])) {
print '<p class="error">Please enter your First Name.</p>';
$validate = FALSE;
}
//validate the last name
if(empty($_POST['lastName'])) {
print '<p class="error">Please enter your Last Name.</p>';
$validate = FALSE;
}
//validate the enail with email arrary
if(!isValidEmail($_POST['email'])) {
print '<p class="error">Please enter your Email Address in the correct formate.</p>';
$validate = FALSE;
}
//validate the phone number
if(is_numeric($_POST['phone01'])) {
$phone = $_POST['phone01']. '-';
}elseif(is_numeric($_POST['phone02'])) {
$phone .= $_POST['phone02']. '-';
}elseif(is_numeric($_POST['phone03'])) {
$phone .= $_POST['phone03'];
}else{
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
//validate the message
if(empty($_POST['message'])) {
print '<p class="error">Please enter your Messagee.</p>';
$validate = FALSE;
}
if(!$validate){
print "<p>Please fill in all the fields with an asterisk * next to it and than please try again!</p>";
show_form($_POST['firstName'],$_POST['lastName'],$_POST['businessName'],$_POST['email'],$_POST['phone01'],$_POST['phone02'],$_POST['phone03'],$_POST['message']);
}else{
$phone01 = $_POST['phone01'];
$phone02 = $_POST['phone02'];
$phone03 = $_POST['phone03'];
$phone = $phone01.'-'.$phone02.'-'.$phone03;
//confirmation email to client includes all information provided
mail($_POST['email'], 'Contact Confirmation from www.Ozbar.net Web site', 'Thank You '.$_POST['firstName'].' '.$_POST['lastName'].' for your request for us to contact you.
Below is the information your provided us to contact you per your request.
First Name: '.$_POST['firstName'].'
Last Name: '.$_POST['lastName'].'
Business Name: '.$_POST['businessName'].'
Email Address: '.$_POST['email'].'
Phone Number: '.$_POST['phone01'].'-'.$_POST['phone02'].'-'.$_POST['phone01'].'
Message: '.$_POST['message'].' ','From:contact#steveoatman.me);
//notice of a new contact request
mail('contact#steveoatman.me, 'Contact Request from www.Steveoatman.me Web site', '
First Name: '.$_POST['firstName'].'
Last Word: '.$_POST['lastName'].'
Business Name: '.$_POST['businessName'].'
Email Address: '.$_POST['email'].'
Phone Number: '.$_POST['phone01'].'-'.$_POST['phone02'].'-'.$_POST['phone01'].'
Message: '.$_POST['message'].' ','From:contact#steveoatman.me);
print '<p align="center">Thank You For Your Request!</p>'?><br /><?php
print '<p align="center">We will contact you back with in 24-48 hours.</p>'
?>
<br /><br /> <!-- if all validated a thank you statement -->
<?php
}
} //end of IF submit
// end of all php
?>
<!-- end of #ref form -->
Use strlen to validate the field lengths. Do not use if/elseif as you want to verify all three inputs. Set a flag to keep track of the validity of the phone number.
$invalid_phone = false;
if((strlen($_POST['phone01']) == 3) && is_numeric($_POST['phone01'])) {
$phone = $_POST['phone01']. '-';
}else{
$invalid_phone = true;
}
if((strlen($_POST['phone02']) == 3) && is_numeric($_POST['phone02'])) {
$phone .= $_POST['phone02']. '-';
}else{
$invalid_phone = true;
}
if((strlen($_POST['phone03']) == 4) && is_numeric($_POST['phone03'])) {
$phone .= $_POST['phone03'];
}else{
$invalid_phone = true;
}
if($invalid_phone){
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
The code above is just checking whether any of the 3 fields have a number in them, rather than all of them.
To achieve what you are going for above, something like this would do it:
if (is_numeric($_POST['phone01']) && is_numeric($_POST['phone02']) && is_numeric($_POST['phone03']))
{
$phone = $_POST['phone01']."-".$_POST['phone02']."-".$_POST['phone03'];
}
else
{
print '<p class="error">Please enter your Phone Number as 10 Number.</p>';
$validate = FALSE;
}
However, the above code does not do any other kind of validation, such as checking to see that the required number of digits have been put in each form field.
You might also want to use the 'ctype_digit()' function to make sure that only digits are entered, rather than a numric string such as 1.3.
So you could do something like
if (!ctype_digit($_POST['phone01']) || strlen($_POST['phone01']) != 4)
{
$validate = FALSE;
}