PHP Forms Trouble with the elusive $_POST - php

Hey Guys this should be probably really simple I am just missing a step.
So I have a form and I want to make sure all values are added before moving to the next page that processes my values and sends them to my email. I also have error messages if someone does not add a value. The error messages display on the reloading of the page.
The problem I have is that you have to reload the page for the Superglobal Post to contain any values. For some reason it does not add them until the page is reloaded. So what happens is if you fill all 5 input fields you have to reload the page, and then submit again for it to send it to my send_form_email.php script because at that point the values are added. I want it to logically reload if any of the values are empty (which will display error messages telling the user that the input field must have content), and automatically send the user to send_form_email.php if all values have been correctly added.
It's almost pull my hair out so if someone could help me understand what piece of the puzzle I am missing I would be so grateful!
<form name="contactform" method="post" action="<?php echo $value; ?>">
<table width="450px">
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="firstname" type="text" name="first_name" maxlength="50" size="30" placeholder="name"><br>
<span class="error">* <?php echo $firstErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="lastname" type="text" name="last_name" maxlength="50" size="30">
<span class="error">* <?php echo $lastErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="email" type="text" name="email" maxlength="80" size="30">
<span class="error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<input class="inputs" placeholder="telephone" type="text" name="telephone" maxlength="30" size="30">
<span class="error">* <?php echo $telephoneErr;?></span>
</td>
</tr>
<tr>
<td valign="top">
</td>
<td valign="top">
<textarea class="inputs" placeholder="comments" name="comments" maxlength="1000" cols="25" rows="6"></textarea>
<span class="error">* <?php echo $commentsErr;?></span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit" style="background-color: #0F6D87;
font-family: Exo-Light;
color: #000000;
width: 75px;
font-weight: bold;
border-color: #003D69;
border-style: outset;
font-size: .8em;
box-shadow: 2px 2px 2px rgba(0, 34, 97, 0.6);">
<INPUT TYPE="RESET">
</td>
</tr>
</table>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (!empty($_POST["first_name"]) && !empty($_POST["last_name"]) && !empty($_POST["email"]) && !empty($_POST["telephone"]) && !empty($_POST["comments"])) {
$value ="http://cdubach.com/inc/send_form_email.php";
} elseif (empty($_POST["first_name"]) || empty($_POST["last_name"]) || empty($_POST["email"]) || empty($_POST["telephone"]) || empty($_POST["comments"])){
$value = "#";
}
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
echo $_POST['submit'] . " = Submit <br>";
echo $_POST["first_name"] . " = First Name <br>";
echo $_POST["last_name"] . " = Last Name <br>";
echo $_POST["email"] . "= Email <br>";
echo $_POST["telephone"] . "= Telephone <br>";
echo $_POST["comments"] . "= Comments <br>";
echo var_dump($_Post) . "= Dump <br>";
echo $value . " = Value <br>" ;
echo $_SERVER["PHP_SELF"];
header('Content-Type: text/plain');
var_dump(htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES, 'UTF-8'));
echo "<br>";
echo htmlspecialchars("<a href='test'>Test</a>", ENT_XHTML, 'UTF-8');
echo "<br>";
$str = "A 'quote' is <b>bold</b>";
/* */
//convert from utf8
$str = utf8_decode($str);
//translate HMTL entities
$trans = get_html_translation_table(HTML_ENTITIES);
$str = strtr($str, $trans);
echo htmlspecialchars($str);
echo "<br>";
echo htmlentities($str, ENT_QUOTES);
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Check First Name Field if Nothing Post Error
if (empty($_POST["first_name"])) {
$firstErr = "Name is required";
} else {
$firstErr = test_input($_POST["name"]);
}
//Check Last Name Field if Nothing Post Error
if (empty($_POST["last_name"])) {
$lastErr = "Last Name is required";
} else {
$lastErr = test_input($_POST["last_name"]);
}
//Check Email Field if Nothing Post Error
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$emailErr = test_input($_POST["email"]);
}
//Check Telephone Field if Nothing Post Error
if (empty($_POST["telephone"])) {
$telephoneErr = "Telephone is Required";
} else {
$telephoneErr = test_input($_POST["telephone"]);
}
//Check Comments Field if Nothing Post Error
if (empty($_POST["comments"])) {
$commentsErr = "Comments is Required";
} else {
$commentsErr = test_input($_POST["comments"]);
}
//Check Comments
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

The reason you need to reload a second time in order for the script to work is because the action property of the form is not populated on the first run (since $value is not set), on the 2nd run however it is (if the $_POST pass the checks you have set) and is set to http://cdubach.com/inc/send_form_email.php.
You will see this if you check the actual html code in the first and second run.
However this is only one of the problems with your script. Some hints:
remove the header('Content-Type: text/plain');, that line instructs the browser to treat the page as text and it will not render it as html.
move the whole html after your PHP script - that way the errors messages you have prepared will work as they should
finally to resolve your problem with "$_POST only if all ok" condition check the validity of the script with client side JavaScript. On another hand if you have access over the called script (the one that $value points to) you could make the check there and redirect to the form if you should.

Related

Registration redirecting even with validation errors [closed]

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 7 years ago.
Improve this question
I have created a php registration page. Everything is running well. It shows an error when I leave text box empty.
However when I use the action method to redirect the registration page, it's always redirecting, both when I am writing something and when I'm not entering something in the text box.
I want that the page doesn't redirect when the field is empty. I use a boolean and the break method, but nothing is happening.
Can anyone help me here on this issue?
<html>
<?php
include 'header.php';
$nameErr = $emailErr = $genderErr = $passwordErr = $addErr = $phoneErr = "";
$fullname = $email = $gender = $password = $address = $phone = "";
$flag = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
break;
$flag
}
else {
$fullname = test_input($_POST["fullname"]);
}
if (empty($_POST["password"])) {
$passwordErr = " password required";
break;
}
else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
break;
}
else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["address"])) {
$addErr = "Address required";
break;
}
else {
$gender = test_input($_POST["address"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
break;
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone no required";
break;
} else {
$phone = test_input($_POST["phone"]);
}
}
?>
<body>
<br>
<div class="regis_div" >
<form name="myForm" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post" action="thanks.php" >
<table class="table2" border="0" align="center" cellspacing="15" >
<tr>
<td colspan="3"><h1><center>User Registration Form</center></h1></td>
</tr>
<tr>
<td width="291">       Full name:</td>
<td width="150"><input type="text" name="fullname"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $nameErr;?></span></font></td>
</tr>
<tr>
<td>      Password</td>
<td><input type="password" name="password"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td>      Confirm Password</td>
<td><input type="password" name="Confirmpassword"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td>      Email Address:</td>
<td><input type="text" name="email" ></td>
<td><span class="error"><font size="2" color="red">* <?php echo $emailErr;?></span></td>
</tr>
<tr>
<td>      Gender:</td>
<td><input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male</td>
<td><span class="error"><font size="2" color="red">* <?php echo $genderErr;?></span></td>
</tr>
<tr>
<td height="80">      Address:</td>
<td><textarea type="text" name="Address" class="address" rows="4" cols="20" ></textarea></td>
<td><span class="error"><font size="2" color="red">* <?php echo $addErr;?></span></td>
</tr>
<tr>
<td>      Phone No:</td>
<td><input type="text" name="phone"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $phoneErr;?></span></td>
</tr>
<tr>
<td colspan="2"><input class="regbtn2" type="submit" value="Submit" align="center" ></td>
</tr>
</table>
</form>
</div>
</body>
</html>
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
break;
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone no required";
break;
} else {
$phone = test_input($_POST["phone"]);
}
break will only break out of for, foreach, while, do-while and switch structures, not if statements.
It's also unclear exactly which script you believe should be handling your form submission:
<form name="myForm" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post" action="thanks.php" >
If the script you posted above is named form.php, then the above line will produce the following (invalid) markup:
<form name="myForm" form.php method="post" action="thanks.php" >
When submitted, execution will immediately flow to thanks.php and none of your PHP error checking (as posted above) will run. If you want the code you posted above to run, you should change that form tag to this:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
Then, once you're satisfied that your submission has no errors, you can redirect the user to a new page:
header('Location: thanks.php');
You should also note that, when that line is executed, you will loose access to all of your existing POST data, so you must do something with it if you wish to preserve it before redirecting with a header.
However, there's quite a few issues with your code.
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
break; // Already mentioned this line will have no effect
$flag // Why is this line here?
}
How will you know, using your current structure, if any error was encountered? It would have to look like this:
if(isset($nameErr) || isset($passwordErr) || isset($emailErr) || ...)
You can simplify that with an array:
if (empty($_POST["fullname"])) {
$errors['name'] = "Name is required";
// ...
}
// ...
if(count($errors)) {
// Some error occurred, don't redirect
} else {
// ... do something with POST data ...
header('Location: thanks.php');
exit; // Always exit or die after issuing a header redirect
}
And the associated markup:
<?php if(isset($errors['name'])) { ?>
<span class="error">
<font size="2" color="red">*
<?php echo $errors['name']; ?>
</font> <!-- Don't forget to close all of your opened HTML tags -->
</span>
<?php } ?>

How to prevent web form from submitting blank fields

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

php email validation (filter_validate_email) Not Working

I know there are numerous questions about this however I just can not seem to pick the error with my coding. I know it is something simple but I can not see it.
I have to create a form which when it is submitted the data will be inputted into MySQL database however the data needs to be validated first. I have 2 issues with this, the first being my email validation is not working using: (filter_var($email, filter_validate_email))
The problem is that when I submit the form it returns true regardless of if the email is valid or not.
If I put (!filter_var($email, filter_validate_email)) it returns false regardless of the input.
The second problem is that when loading the page it initially adds a blank entry into the SQL database and it adds entries that aren’t valid. i.e. if I don’t enter a name when the form is submitted the validation runs and I get the error message “name is required” but it still creates an entry in the table with a blank name.
I am using PHP version 5.3.27
This is for my tafe course i am doing however they are on holidays at the moment so any help would be greatly appreciated.
Coding from file 1:
<body>
<?php
// define variables and set to empty values
$nameErr;
$Name = $Address = $Phone = $Mobile = $Email="example#example.com";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["Name"]))
{$nameErr = "Name is required"; }
else {$Name = test_input($_POST["Name"]);}
if (empty($_POST["Address"]))
{$Address = "";}
else
{$Address = test_input($_POST["Address"]);}
if (empty($_POST["Phone"]))
{$Phone = "";}
else
{$Phone = test_input($_POST["Phone"]);}
if (empty($_POST["Mobile"]))
{$Mobile = "";}
else
{$Mobile = test_input($_POST["Mobile"]);}
if(filter_var($Email, FILTER_VALIDATE_EMAIL)){
echo"Valid Email";
}
else{
echo "Not a Valid Email";
}
echo phpinfo();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form name="addcontact" method="post" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", "add-contact.php">
<table border="1" cellpadding="2">
<caption> Add New Caption </caption>
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="Name" size="30" maxlenght="50" tabindex="1"/> <span class="error">*<?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td><label for="Address">Address</label></td>
<td><textarea name="Address" cols="45" rows="5" tabindex="2"></textarea></td>
</tr>
<tr>
<td><label for="Phone">Phone</label></td>
<td><input type="text" name="Phone" size="20" maxlenght="20" tabindex="3" /> </td>
</tr>
<tr>
<td><label for="Mobile">Mobile</label></td>
<td><input type="text" name="Mobile" size="20" maxlenght="20" tabindex="4" /> </td>
</tr>
<tr>
<td><label for="Email">Email</label></td>
<td><input type="text" name="Email" size="30" maxlenght="50" tabindex="5" /></td>
</tr>
<tr>
<td colspan"2" align="center"><input type="Submit" name="Submit" value="Submit" tabindex="6"/>
</td>
</tr>
</table>
</form>
<?php
include("add-contact.php");
?>
</body>
</html>`
And coding from file 2:
<body>
<?php
$Name = $_POST["Name"];
$Address = $_POST["Address"];
$Phone = $_POST["Phone"];
$Mobile = $_POST["Mobile"];
$Email = $_POST["Email"];
$dbc = mysql_connect("localhost:3306", "root", "webbm01");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
$qry
= "INSERT INTO contacts (Name, Address, Phone, Mobile, Email) VALUES ('" . addslashes($Name) . "', '" . addslashes($Address) . "', '" . addslashes($Phone) . "', '" . addslashes($Mobile). "', '" . addslashes($Email) . "')";
$rst = mysql_query($qry, $dbc);
if ($rst)
{
echo "<b><font color='green'>The contact has been added.</font></b>";
}
else
{
echo "<b><font color='red'>Error: ". mysql_error($dbc) . ". The contact could not be added.</font></b>";
}
mysql_free_result($rst);
?>
</body>
</html>
check this code for email validation etc :
<body> <?php
// define variables and set to empty values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {$nameErr = "Name is required"; }else {$Name = htmlspecialchars($_POST["Name"]);}
if (empty($_POST["Address"])) {$Address = "";}else{$Address = htmlspecialchars($_POST["Address"]);}
if (empty($_POST["Phone"])) {$Phone = "";}else {$Phone = htmlspecialchars($_POST["Phone"]);}
if (empty($_POST["Mobile"])) {$Mobile = "";}else {$Mobile = htmlspecialchars($_POST["Mobile"]);}
if(filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL)){ echo"Valid Email"; }else{ echo "Not a Valid Email"; }
}
?>
<form name="addcontact" method="post" action= "<?php echo $_SERVER["PHP_SELF"];?>">
<table border="1" cellpadding="2"> <caption> Add New Caption </caption> <tr> <td><label for="Name">Name</label></td> <td><input type="text" name="Name" size="30" maxlenght="50" tabindex="1"/> <span class="error">*<?php echo $nameErr;?></span> </td> </tr>
<tr> <td><label for="Address">Address</label></td> <td><textarea name="Address" cols="45" rows="5" tabindex="2"></textarea></td> </tr>
<tr> <td><label for="Phone">Phone</label></td> <td><input type="text" name="Phone" size="20" maxlenght="20" tabindex="3" /> </td> </tr>
<tr> <td><label for="Mobile">Mobile</label></td> <td><input type="text" name="Mobile" size="20" maxlenght="20" tabindex="4" /> </td> </tr> <tr> <td><label for="Email">Email</label></td> <td><input type="text" name="Email" size="30" maxlenght="50" tabindex="5" /></td> </tr> <tr> <td colspan"2" align="center"><input type="Submit" name="Submit" value="Submit" tabindex="6"/> </td> </tr> </table> </form>
</body> </html>`
The validation should happen in the file:
'add-contact.php'
Since this is what the from action is calling on submit.
The initial validators are meaningless since the $_POST array is not initialized.
The reason for the empty SQL insert statement is because you decide to do:
include("add-contact.php");
In the first file and it is running without valid $_POST initialization on each load of the page.
Remove the line include("add-contact.php");
This will stop the blank insertion in the database.
Also remove the action
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
Just try action="add-contact.php".
Email validation is working fine for me.

PHP Form Send - Save Data to Table, send activation email?

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.

PHP contact form phone validation of the correct amount of numbers

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;
}

Categories