Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here is the form.
When I click submit without entering any required data, I do not see the error message, it just jumps to the top of the page. How can I fix this?
The PHP validation code added to the head of the form is:
if ($_POST['submit'])
{
/* Check all form inputs and strip unnecessary characters from data */
$quotetype = $_POST['quotetype'];
$name = check_input($_POST['name']);
$phone = check_input($_POST['phone']);
$email = check_input($_POST['email']);
$zipcode = check_input($_POST['zipcode']);
$appgender = $_POST['appgender'];
$appdob = check_input($_POST['appdob']);
$appsmoker = $_POST['appsmoker'];
$spousedob = check_input($_POST['spousedob']);
$spousesmoker = $_POST['spousesmoker'];
$child1gender = check_input($_POST['child1gender']);
$child1dob = check_input($_POST['child1dob']);
$child2gender = check_input($_POST['child2gender']);
$child2dob = check_input($_POST['child2dob']);
$child3gender = check_input($_POST['child3gender']);
$child3dob = check_input($_POST['child3dob']);
$child4gender = check_input($_POST['child4gender']);
$child4dob = check_input($_POST['child4dob']);
$currentcarrier = check_input($_POST['currentcarrier']);
$carriertype = $_POST['carriertype'];
$coverage = $_POST['coverage'];
$deductible = check_input($_POST['deductible']);
$premium = check_input($_POST['premium']);
$officecopay = check_input($_POST['officecopay']);
$rxcopay = check_input($_POST['rxcopay']);
$medconditions = $_POST['medconditions'];
$coverageamount = $_POST['coverageamount'];
$comments = $_POST['comments'];
if (is_array($quotetype))
$displayquotetype = implode(",",$quotetype);
$errorstring = ""; //default value of error string
/* Check for required fields */
if (empty($quotetype))
$errorstring = $errorstring."*Quote Type ";
if (!$name)
$errorstring = $errorstring."*Name ";
if (!$phone)
$errorstring = $errorstring."*Phone ";
if (!$email)
$errorstring = $errorstring."*Email ";
if (!$zipcode)
$errorstring = $errorstring."*Zip Code ";
if ($appgender=="choose")
$errorstring = $errorstring."*Gender ";
if ($appsmoker=="choose")
$errorstring = $errorstring."*Smoker";
if ($errorstring =="") {
$to = 'name#domain.com';
$subject = 'Quote Request';
$message = " <html><body> </body></html> ";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
mail($to,$subject,$message,$headers);
header('location: messagesent.html');
exit();
}
}
/* Functions used */
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Form within index.php:
<form id="quote-form" name="quote-form" method="post" action="index.php">
...
<?php
if ($errorstring!="")
{echo "<span class='errormessage'>Please fill out the following fields: $errorstring<br></span>";}
?>
...
</form>
Add "name" attribute to your submit input.
<input type="submit" class="rounded-button button-shadow" id="submit" value="Submit" name="submit" />
Related
I'm in need of some help with my PHP query. I'm essentially giving users the opportunity to update their own details once they have logged in. The form:
<div class="grid-2">
<p><b>UPDATE MY DETAILS</b></p>
<form action ="includes/update.inc.php" method ="post">
<label>S.Name</label>
<input name="update-surname" type="text" placeholder="Enter new surname...">
<label>Address</label>
<input name="update-houseno" type="text" placeholder="Enter house no' or name...">
<input name="update-ln1" type="text" placeholder="1st Line of Address...">
<input name="update-town" type="text" placeholder="Town...">
<input name="update-county" type="text" placeholder="County...">
<input name="update-postcode" type="text" placeholder="Postcode...">
<label>Contact Number</label>
<input name="update-number" type="text" placeholder="Contact Number...">
<label>Email</label>
<input name="update-email" type="text" placeholder="Email...">
<input type="submit" name="update-details" value="Update">
</form>
</div>
My php code which I have currently, if the user doesn't enter anything in the box, it updates the database with a blank input (which I don't want to happen), if there's no input I don't want that field in the table touched.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET `fldSName` = '$surname', `fldTelNum` = '$number', `fld1stLnAddress` = '$houseno', `fld2ndLnAddress` = '$ln1', `fld3rdLnAddress` = '$town', `fldCounty` = '$county', `fldPostcode` = '$postcode', `fldEmailAddress` = '$email' WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
?>
Once the php form is loaded, the web page disappears and doesn't stay on the current webpage their on either.
So 2 things needed, help with the correct query and help with the page going blank and not staying on the webpage.
Please note that I know this is vulnerable to injection attack I'm just trying to get it physically working before I attempt to get my head around how I do prepared statements.
Thanks!
You need to check if data input field is non-empty/valid.
Steps to avoid blank fields update:
1) Take an empty array
2) Check if every posted variable is valid, if it valid append it to array.
3) Check if the array is not empty.
4) If its not empty, fire SQL.
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$ln1 = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$update = [];
if (! empty($surname)) {
$update['fldSName'] = "fldSName = '".$surname ."'";
}
if (! empty($number)) {
$update['fldTelNum'] = "fldTelNum='".$number ."'";
}
if (! empty($houseno)) {
$update['fld1stLnAddress'] = "fld1stLnAddress='".$houseno ."'";
}
if (! empty($ln1)) {
$update['fld2ndLnAddress'] = "fld2ndLnAddress='".$ln1 ."'";
}
if (! empty($town)) {
$update['fld3rdLnAddress'] = "fld3rdLnAddress='".$town ."'";
}
if (! empty($county)) {
$update['fldCounty'] = "fldCounty='".$county ."'";
}
if (! empty($postcode)) {
$update['fldPostcode'] = "fldPostcode='".$postcode ."'";
}
if (! empty($email)) {
$update['fldEmailAddress'] = "fldEmailAddress='".$email ."'";
}
if (! empty($update)) {
$query = "UPDATE `tblMember` SET ";
$query .= implode(', ', $update);
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query) or die ("error");
}
}
?>
NOTE:
fldMemberID seems to be hard-coded.
For first concern you can edit your query as
UPDATE tblMember
SET fldSName = IF('$surname' = '', fldSName, '$surname'),
fldTelNum = IF('$number' = '', fldTelNum, '$number'),
fld1stLnAddress = IF('$houseno' = '', fld1stLnAddress, '$houseno'),
fld2ndLnAddress = IF('$ln1' = '', fld2ndLnAddress, '$ln1'),
fld3rdLnAddress = IF('$town' = '', fld3rdLnAddress, '$town'),
fldCounty = IF('$county' = '', fldCounty, '$county'),
fldPostcode = IF('$postcode' = '', fldPostcode, '$postcode'),
fldEmailAddress = IF('$email' = '', fldEmailAddress, '$email'),
WHERE
`tblMember`.`fldMemberID` = 1
For Second concern you have to remove die() and redirect to after-login.php as
$conn->query($query);
header("Location: ../after-login.php");
<?php
// Here we check whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {
require 'dbh.inc.php';
// We grab all the data which we passed from the signup form so we can use it later.
$surname = $_POST['update-surname'];
$houseno = $_POST['update-houseno'];
$ln1 = $_POST['update-ln1'];
$town = $_POST['update-town'];
$county = $_POST['update-county'];
$postcode = $_POST['update-postcode'];
$email = $_POST['update-email'];
$number = $_POST['update-number'];
// We validate the updated email is correct if email has been updated.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../after-login.php?error=invalidmail=");
exit();
}
$query = "UPDATE `tblMember` SET ";
(!empty($surname))?: $query .= "`fldSName` = '$surname',";
(!empty($houseno))?: $query .= "`fldTelNum` = '$houseno',";
(!empty($ln1))?: $query .= "`fld1stLnAddress` = '$ln1',";
(!empty($town))?: $query .= "`fld2ndLnAddress` = '$town',";
(!empty($county))?: $query .= "`fld3rdLnAddress` = '$county',";
(!empty($postcode))?: $query .= "`fldCounty` = '$postcode',";
(!empty($email))?: $query .= "`fldPostcode` = '$email',";
(!empty($number))?: $query .= "`fldEmailAddress` = '$number'";
$query .= " WHERE `tblMember`.`fldMemberID` = 1";
$result = $conn->query($query);
header("Location: ../after-login.php"); //make sure of the path
}
Basically you are checking your input values and like that you build your query by concatenating the query blocks.
At the end added the header to redirect you to the page you want.
When I try to get my contact form working, my browser crashes and sends me a white page. I have found the reason, but I cannot understand what is wrong.
//getting fields
$naam = $_POST['naam'];
$email = $_POST['email'];
$adres = $_POST['adres'];
$postcode = $_POST['postcode'];
$telefoon = $_POST['telefoon'];
$iban = $_POST['iban'];
$15 = $_POST['15'];
$20 = $_POST['20'];
$25 = $_POST['25'];
$30 = $_POST['30'];
$anderbedrag = $_POST['anderbedrag'];
//message to webmaster
$message = $naam;
$message .= "jaarlijks bijdrage: ";
if ($15 != null){
$message .= '15,-';
}
if ($15 != null){
$message .= '20,-';
}
if ($15 != null){
$message .= '25,-';
}
if ($15 != null){
$message .= '30,-';
}
if ($anderbedrag != null){
$message .= $anderbedrag;
}
From the docs:
A valid variable name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores.
So your variable names aren't valid ($15 etc).
Besides that; always enable error reporting when developing. Php would have told you this.
ini_set('display_errors', 1);
error_reporting(E_ALL);
The form inputs aren't displaying on the form.php page and negates my form validation. The error says undefined variable for all my variables on form.php. Please tell me what I have to edit in my code to make it display the form inputs on form.php. It works when I use it on the same page but I would rather it display on another page.
EDIT
Thanks so far but I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A".
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>
If you would like to transfer the data from contact.php to form.php you should use something like this:
contact.php
$data = urlencode(
serialize(
array(
"name" => $name,
"email" => $email,
"subject" => $subject,
"message" => $message)
));
header('Location: form.php?data=' . $data);
form.php
$data = unserialize(urldecode($_GET['data']));
$name = $data["name"];
$email = $data["email"];
$subject = $data["subject"];
$message = $data["message"];
This serializes the array of data from contact.php then URL encodes it and sends it as a GET variable to form.php. After, form.php URL decodes and unserializes the data for use.
The problem is when you header("Location:") to form.php, all the POST values are lost. You have to either resend them with the header, or modify them into GET and retrieve them again. It should be more efficient to have them both (contact.php AND form.php) in one page. That way, the form data only has to be sent once.
You could probably just send the POST values as GET over to form.php like this.
contact.php:
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject."&message=".$message);
form.php (to retrieve the values):
$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];
$subject = $_GET['subject'];
If you want to display form elements then you have to use this approach.
<form method="POST" action="contact.php">
Email<input type="text" name="email">
.......
.......
.......
// All elements
</form>
This may help you.
Give action in your form in contact.php
<form action="form.php">
Ok here is a shortened version of the php for my contact form, (the checkboxes are not being sent through correctly)
<?php
//please fill this in at least!
$myemail = "";
$title = "Feedback Form";
if(isset($_POST['submit'])) { //form has been submitted
//set variables with filters
$cont_name = filter_var($_POST['cont_name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['cont_email'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['cont_phone'], FILTER_SANITIZE_STRING);
$first_time = filter_var($_POST['first_time'], FILTER_SANITIZE_STRING);
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
function valid_email($str){
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;}
$errors = 0; //by default there are no errors
$trimcont_name = trim($cont_name);
if(empty($trimcont_name)){
//the name field is empty
$errors = 1; //tips off the error messages below
$errorcont_name = "The name field is empty"; //this error is displayed next to the label
}
if(!valid_email($email)) {
//email is invalid or empty
$errors = 1;
$erroremail = "The email address was not valid";
}
$trimphone = trim($phone);
if(empty($trimphone)){
//the phone field is empty
$errors = 1;
$errorphone = "The phone field is empty";
}
$trimfirst_time = trim($first_time);
if(empty($trimfirst_time)){
//the first_time field is empty
$errors = 1;
$errorfirst_time = "This field is empty";
}
$trimhear_about = trim($hear_about);
if(empty($trimhear_about)){
//the hear_about field is empty
$errors = 1;
$errorhear_about = "This field is empty";
}
if($spam != "") {
//spam was filled in
$errors = 1;
$errorspam = "The Spam box was filled in";
}
if($errors == 0) {
$sendto = $myemail;
$message = <<<DATA
DETAILS
Name: $cont_name
Email: $email
Phone: $phone
Was this the first time you have been to us?
$first_time
How did you hear about us?
$hear_about
DATA;
$headers = 'From: ' . $name . '<' . $email . '>';
if(mail($sendto, $title, $message, $headers)) {
//this is where it sends, using the php mail function
$success = true;
//set all the variables to blank to prevent re-submitting.
$cont_name = "";
$email = "";
$phone = "";
$hear_about = "";
$first_time = "";
} else {
$success = false;
}
} else {
$success = false;
}
}
?>
And the area not functioning correctly is
<fieldset>
<legend>How did you hear about us? <span class="phpformerror"><?php echo $errorhear_about; ?></span></legend>
<div><input type="checkbox" name="hear_about[]" value="Web" /> Web</div>
<div><input type="checkbox" name="hear_about[]" value="Newspaper" /> Newspaper</div>
<div><input type="checkbox" name="hear_about[]" value="Radio" /> Radio</div>
<div><input type="checkbox" name="hear_about[]" value="Driving" /> Driving Past</div>
<div><input type="checkbox" name="hear_about[]" value="Referal" /> Referal</div>
<div><input type="checkbox" name="hear_about[]" value="Other" /> Other</div>
</fieldset>
At the moment it will only come through displaying one of the variables if multiple variables are selected.
hear_about is an array and filter_var() does not handle arrays correctly. Instead use filter_var_array():
$hear_about = filter_var_array($_POST['hear_about'], FILTER_SANITIZE_STRING);
Remember that $hear_about is an array, and must be treated like one throughout your code (e.g. just using $hear_about won't work, it needs to be $hear_about[0], $hear_about[1], etc).
So for example in your trim line you would need something like:
foreach($hear_about as $key => $value) {
$trimhear_about[$key] = trim($value);
if(empty($trimhear_about[$key])){
//the hear_about field is empty
$errors = 1;
$errorhear_about[$key] = "This field is empty";
}
}
This will preserve the benefits of dealing with an array.
$_POST['hear_about'] is an array of values. You are handling it as a simple string!
I think you can solve simply replacing the line:
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
With:
$hear_about = filter_var(implode(', ', $_POST['hear_about']), FILTER_SANITIZE_STRING);
The implode function (doc) "transform" an array to a string by concatenating the array values with the given glue. So you can just concatenate selected "How did you hear about us?" options with a comma and then use the resulting string as the other data.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to validate an email address in PHP
I was wondering someone can help me please.
I need to validate the email address for the below code but am having problems.
<?php
if ($_POST) {
$expected = array('name', 'email', 'emailmessage');
$validation = array(
'name' => 'Please provide your full name',
'email' => 'Please provide your valid email address',
'emailmessage' => 'Please provide message'
);
$errors = array();
$output = array();
foreach($expected as $key) {
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
if (empty($_POST[$key])) {
$errors[$key] = $validation[$key];
} else {
$output[$key] = $_POST[$key];
}
} else {
$errors[$key] = $validation[$key];
}
}
if (!empty($errors)) {
$array = array('error' => true, 'fields' => $errors);
} else {
// PROCESS FORM
// ---------------------------------------------------------
// BEGIN EDITING
// ---------------------------------------------------------
$to = "qakbar#hotmail.co.uk"; //This is the email address messages will be sent to
$web_name = "My Test Web Form"; //This is the name of your website that will show in your email inbox
//get IP address
$ip = $_SERVER['REMOTE_ADDR'];
//make time
$time = time();
$date = date("r", $time);
// ---------------------------------------------------------
// END EDITING
// ---------------------------------------------------------
$emailmessage = trim($emailmessage);
$emailmessage = nl2br($emailmessage);
$emailmessage = htmlspecialchars($emailmessage);
$emailmessage = wordwrap($emailmessage, 70);
//Visible form elements
$name = $_POST['name']; //Sender's name
$email = $_POST['email']; //Sender's email
$emailmessage = htmlspecialchars($_POST['emailmessage']); //Sender's message
//Setting up email
$subject = "New Message from $web_name";
$message = "
New message from $name <br/><br/>
Message:<br />
$emailmessage
<br/>
<br/>
Email: $email<br />
IP:</strong> <span style=\"color:#990000;\">$ip</span><br />
Date:</strong> $date
";
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$header .= 'From:'. $email . " \r\n";
$sent = mail($to, $subject, $message, $header);
//$message = '<div id=message>You have successfully subscribed to our newsletter</div>';
$array = array('error' => false, 'message' => $message);
}
echo json_encode($array);
}
I want the email to validate in the $validation array as my messages are passed through this and need the email validation to do the same.
I was trying to use the following but did not know where to place it or how to call it.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// email is valid
} else {
// email is invalid
}
Any help is much apprecaited.
Thank you
You could use it like this:
filter_var($email, FILTER_VALIDATE_EMAIL) or die("Email wrong.");
Right after you assigned this exact variable:
$email = $_POST['email'];
Of course this could be structured more sensible, and a nicer error notice would also be possible. But it sounds as if you need more general practice with PHP first.
An oddity with your code:
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
You're using the key already BEFORE checking if it exists. As well, the $input variable is not used again in your code, so it's a useless line.
May be, this code will help you. try it.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>