How to handle repeating form inputs in PHP? - php

I have a form to email php script. The context of the website makes it necessary for me to add repeating form fields at the User's click of a button. How do I properly handle the form input? For example I have a Vehicle form and when the User click's add vehicle I append a carbon copy of several of the vehicle's form groups. These form inputs have the same "name" and there for php is trying to access two or more form inputs of the same name in my script.
Should I store the inputs as an array somehow?
Here is my script:
<?php
$admin_email = "email#gmail.com";
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$carrier = $_POST['carrier'];
$yes = $_POST['yes'];
$no = $_POST['no'];
$renewal = $_POST['renewal'];
$homephone = $_POST['homephone'];
$cellphone = $_POST['cellphone'];
$year = $_POST['year'];
$makemodel = $_POST['makemodel'];
$twowd = $_POST['twowd'];
$fourwd = $_POST['fourwd'];
$vin = $_POST['vin'];
$damage = $_POST['damage'];
$payment = $_POST['payment'];
$umuim = $_POST['umuim'];
$drivername = $_POST['drivername'];
$driverbday = $_POST['driverbday'];
$ssn = $_POST['ssn'];
$dlnumber = $_POST['dlnumber'];
$dlstate = $_POST['dlstate'];
$violations = $_POST['violations'];
$email_body = "Auto Quote\n From: $email \n $address, $carrier, $yes, $no, $carrier, $renewal, $homephone, $cellphone, $year, $makemodel, $twowd, $fourwd, $vin, $damage, $payment, $umuim, $drivername, $driverbday, $ssn, $dlnumber, $dlstate, $violations)";
mail($admin_email, "Auto Quote Request", $email_body);
echo "Thank you for contacting us!";
?>
So when I press the "add vehicle button" I append a copy of the form groups on my form from $year to $umuim. Is my current code capable of handling this? I have not had any errors when testing manually (I can't see what the email looks like as I don't have a mail server in development), but the echo statement at the end works.
One problem I could see is would the variable just reset after receiving the second input. Should I use an array somehow? Thanks.

In HTML when you want multiple fields with the same name you use
<input type="text" name="fieldname[]" ....>
<input type="text" name="fieldname[]" ....>
<input type="text" name="fieldname[]" ....>
The when the data is posted to PHP there should be a field in the $_POST array called fieldname $_POST['fieldname']
You then process that like
foreach ( $_POST['fieldname'] as a_name ) {
echo $a_name;
}

Related

Email mysql query after multi page php form

I've successfully created a multi page php form that uploads all the data to a mysql database. Now I'm trying to get this mail function to work with it, so we can get an email each time someone successfully completes the form.
I'm getting the email now but not the information from the form.
I'm not sure what I'm doing wrong, I'm guessing it's something to do with SESSION but I'm having a hard time actually finding a solution.
Here's the code I'm working with:
<?php
session_start();
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']); // Function to extract array
$connection = mysql_connect("mysql.database.com", "r-----a", "An-----1!");
$db = mysql_select_db("---------", $connection); // Storing values in database.
$query = mysql_query("insert into detail (whenadded,yourname,reservationid,reservationname,property,eta,cellphone,email,signature,petcontract) values(Now(),'$yourname','$reservationid','$reservationname','$property','$eta','$cellphone','$email','$signature','$petcontract')", $connection);
/* Set e-mail recipient */
$myemail = "blahblahblah#retreatia.com";
$yourname = ($_POST['yourname']);
$reservationid = ($_POST['reservationid']);
$reservationname = ($_POST['reservationname']);
$property = ($_POST['property']);
$eta = ($_POST['eta']);
$cellphone = ($_POST['cellphone']);
$email = ($_POST['email']);
$petcontract = ($_POST['petcontract']);
/* Let's prepare the message for the e-mail */
$subject = "$yourname has checked in using Express Checkin!";
$message = "
Information of Express Checkin User:
Name: $yourname
Reservation ID: $reservationid
Name on Reservation: $reservationname
Property: $property
Cell Phone: $cellphone
Email: $email
ETA: $eta
Pet Contract: $petcontract
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
if ($query) {
echo '<div class="absolutecenter boxshadows"><img src="../img/thankyoupage.png" class="img-responsive"></div>';
} else {
echo '<p><span>Form Submission Failed!</span></p>';
}
unset($_SESSION['post']); // Destroying session
?>
Also the form is populating all fields in the database successfully and produces the img file from the echo...
Since you did this:
extract($_SESSION['post']); // Function to extract array.
... this block is unnecessary:
$yourname = ($_POST['yourname']);
$reservationid = ($_POST['reservationid']);
$reservationname = ($_POST['reservationname']);
$property = ($_POST['property']);
$eta = ($_POST['eta']);
$cellphone = ($_POST['cellphone']);
$email = ($_POST['email']);
$petcontract = ($_POST['petcontract']);
In fact, it's probably why your variables aren't populating. They're getting overwritten with empty values since $_POST doesn't contain values from previous pages.

php $_SERVER POST methods the new and more efficient style?

i wrote a relatively simple but usable php query logging software a couple of years back and my setup was "plain vanilla" where a form, with a POST method has a separate page that processes the form like below
1) input form displays with a submit button that calls process-form.php
2) process-form.php then processes the form (e.g. enters the data onto a database)
3) process-form.php displays a message if everything is fine or not.
now, when i go through some php tutorials, they are teaching having the form submit upon itself by using $_SERVER
<?php
//use the $_SERVER function to decipher if the POST method has been triggered
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//TODO: Send email, etc.
}
?>
i can see the benefits of of this method as the code remains compact as you just have to go to 1 page only instead of going to other pages if you need to fix something. Is this the prevalent method now? just asking as i am trying to learn. thank you!
You can use isset() or sizeof() or empty()
if (isset($_POST))
{
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//TODO: Send email, etc.
}
OR
if (sizeof($_POST) > 0)
{
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//TODO: Send email, etc.
}
OR
if (!empty($_POST))
{
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//TODO: Send email, etc.
}

after clicking submit on a contact form, how do i stay on the same page in wordpress?

So I created a custom contact form in WordPress, using PHP. The form sends, and I am receiving emails. The problem I'm having is that once you hit submit, it goes to a post page, and doesn't stay on the original page.
I've tried using a session and header location (didn't work)
I also tried putting this in my action"<?php echo $_SERVER['PHP_SELF']; ?>", doesn't work either. (mail just doesn't send it and sends me to 404 page.
So I'm a little stuck, as to fix this problem. Normally I would have no problems if this was a static web page, but because I'm using WordPress, this task seems to be more troublesome.
Here is a link to the website http://www.indianpointresort.ca/
Here is the php validation:
<?php
/*session_start();
if(!isset($_SESSION['afaisfjisjfijfjiwaefjawsefijef'])){
$url = 'http://www.indianpointresort.ca/';
header("Location:home.php?url=$url");
}*/
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
echo "$name | $email | $phone | $subject | $message";
if(isset($_POST['submit'])){
$boolValidationOK = 1;
$strValidationMessage = "";
//validate first name
//validate last name
if(strlen($name)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper first and last name </br>";
}
//email validation:
$emailValidate = validate_email( $email );// calls the function below to validate the email addy
if(!$emailValidate ){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in proper email address </br>";
}
//validate phone
$phone = checkPhoneNumber($phone);
if(!$phone){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill proper phone number </br>";
}
//validate subject
if(strlen($subject)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper subject description </br>";
}
//validate description
if(strlen($message)<3){
$boolValidationOK = 0;
$strValidationMessage .= "Please fill in a proper message </br>";
}
if($boolValidationOK == 1){
//$strValidationMessage = "SUCCESS";
//MAIL SECURITY !!!!!!!
// WE MUST VALIDATE AGAINST EMAIL INJECTIONS; THE SPAMMERS BEST WEAPON
$badStrings = array("Content-Type:",
"MIME-Version:",
"Content-Transfer-Encoding:",
"bcc:",
"cc:");
foreach($_POST as $k => $v){// change to $_POST if your form was method="post"
foreach($badStrings as $v2){
if(strpos($v, $v2) !== false){
// In case of spam, all actions taken here
//header("HTTP/1.0 403 Forbidden");
echo "<script>document.location =\"http://www.bermuda-triangle.org/\" </script>";
exit; // stop all further PHP scripting, so mail will not be sent.
}
}
}
$ip = $_SERVER['REMOTE_ADDR'];
//echo $ip;
/* Spammer List: IP's that have spammed you before ***********/
$spams = array (
"static.16.86.46.78.clients.your-server.de",
"87.101.244.8",
"144.229.34.5",
"89.248.168.70",
"reserve.cableplus.com.cn",
"94.102.60.182",
"194.8.75.145",
"194.8.75.50",
"194.8.75.62",
"194.170.32.252"
//"S0106004005289027.ed.shawcable.net" Phil's IP as test
); // array of evil spammers
foreach ($spams as $site) {// Redirect known spammers
$pattern = "/$site/i";
if (preg_match ($pattern, $ip)) {
// whatever you want to do for the spammer
echo "logging spam activity..";
exit();
}
}
$to = "";
//$subject = " Indian Point";
// compose headers
$headers = "From: Indian Point Resort.\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: PHP/".phpversion();
$message = wordwrap($message, 70);
// send email
mail($to, $subject, $message, $headers);
}
}//end of submit
//validate phone number
function checkPhoneNumber($number){
$number = str_replace("-", "", $number);
$number = str_replace(".", "", $number);
$number = str_replace(" ", "", $number);
$number = str_replace(",", "", $number);
$number = str_replace("(", "", $number);
$number = str_replace(")", "", $number);
if((strlen($number) != 10) || (!is_numeric($number))){
return false;
}else{
return $number;
}
}
//email validation
function validate_email( $senderemail ){ // this is a function; it receives info and returns a value.
$email = trim( $senderemail ); # removes whitespace
if(!empty($email) ):
// validate email address syntax
if( preg_match('/^[a-z0-9\_\.]+#[a-z0-9\-]+\.[a-z]+\.?[a-z]{1,4}$/i', $email, $match) ):
return strtolower($match[0]); # valid!
endif;
endif;
return false; # NOT valid!
}
?>
Here is the form:
<div id="msgForm" class=" msgForm five columns">
<h4>Questions?</h4>
<h5>Send us a message!</h5>
<form id="contactForm" name="contactForm" method="post" action="<?php the_permalink(); ?>">
<p><input type="text" name="name" value="<?php echo $name; ?>" placeholder="name*"/></p>
<p><input type="email" name="email" placeholder="E-mail*"/></p>
<p><input type="text" name="phone" placeholder="Phone #*"/></p>
<p><input type="text" name="subject" placeholder="subject*"/></p>
<p><textarea name="message" placeholder="Message*"></textarea></p>
<p><input type="submit" name="submit" placeholder="Submit"/></p>
<div class="error">
<?php
if($strValidationMessage){
echo $strValidationMessage;
}
?>
</div>
</form>
</div><!--end of form-->
Well, to start off I would remove that gmail account from your info (just to be safe).
Secondly I would advise you to use the sendmail scripts provided by Wordpress.
There are plugins like gravityforms which allow you to make a form and decide all these options without making a static form, nor a new template file for that matter.
You can only change to which page the form will redirect after the refresh (the action will decide that)
If you want it to stay on the same page you can put the page itself in the action and on top put an if statement like
if(isset($_POST['submit'])){
//validation, sendmail, and possibly errors here
}
else{
//show the form
}
anyway, a refreshing webform is as standard as it gets. It's just how it submits things. The only way you could prevent a page is by using jquery or javascript like so: (give your submit an id)
$('#submit').on("click", function(e){
//this prevents any submit functionality (like refresh)
e.preventDefault();
//custom code to get values here and put them in the sendmail function like so:
var message = $('$message').text();
}
Try ajax form submission. And add the insert query in a separate file.

Prefilled Textarea Duplicated after Validation - PHP

I have a message that I need to prepopulate for a textarea. This message can be edited by users.
If there is a form validation error, the message appears to be duplicated each time that an error occurs.
<textarea name="comments" rows="20" style="width:99%;"><?=$fields['comments']?>TEXT
HERE</textarea>
I don't believe that this is an error due to the validation, but rather the field saving the content and adding it to the existing prepopulated message.
Is there a way that I can load the message and have users edit it without duplication?
I can provide any code necessary. I am currently using this code for validation:
https://github.com/benkeen/php_validation
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['senders_email'] = $_POST['senders_email'];
$_SESSION['address'] = $_POST['address'];
$_SESSION['city'] = $_POST['city'];
$_SESSION['state'] = $_POST['state'];
$_SESSION['comments'] = $_POST['comments'];
//e-mail message text
$body=<<<_MSG_
Hello,
$comments
Sincerely,
$name
$address
$city
$state
_MSG_;
$text = strip_tags($body);
$errors = array();
$fields = array();
$success_message = "";
if (isset($_POST['submit']))
{
require_once("validation.php");
$rules = array(); // stores the validation rules
$rules[] = "required,name,Your <em>Name</em> is required.";
$rules[] = "required,senders_email,Your <em>E-mail</em> is required.";
$rules[] = "valid_email,senders_email,Please enter a valid e-mail address.";
$rules[] = "required,address,Your <em>Address</em> is required.";
$errors = validateFields($_POST, $rules);
if (!empty($errors))
{
$fields = $_POST;
}
// no errors! redirect the user to the thankyou page (or whatever)
else
{
mail($to,$subject,$text,$headers);
header( "Location: thanks.php" );
}
}
?>

Validating form and sending a confirmation email on submission

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

Categories