This question already has answers here:
What is the default form HTTP method?
(5 answers)
Closed last year.
So I've been working on creating a contact form. No matter what I try, I can't get it to work. I've read different blogs, how to's, etc. I would love some help. Note: when it says email#email.com, I've input my own email.
HTML:
<div class="col-lg-6 offset-lg-1">
<form action="form-data/formdata.php" class="form-widget form-control-op-02">
<div class="field-wrp">
<input type="hidden" name="to"value="email#email.com">
I won't bore you with all the details of the form fields i.e. name, phone number, email, etc.
PHP:
if (isset($_POST) && sizeof($_POST) > 0) {
$to = $_POST['to']['val']; // <=== Set static email here.
if (isset($_POST['formtype'])) {
unset($_POST['formtype']);
}
if (isset($_POST['to'])) {
unset($_POST['to']);
}
$email_address = $_POST['email']['val'];
$email_subject = "Form submitted by: ".$_POST['name']['val'];
$email_body = "You have received a new message. <br/>".
"Here are the details: <br/><br/>";
foreach ($_POST as $key => $value) {
$email_body .= "<strong>" . $value['label'] . ": </strong> " . $value['val'] . "<br/><br/>";
}
$headers = "From:<$email_address>\n";
$headers.= "Content-Type:text/html; charset=UTF-8";
if($email_address != "") {
mail($to,$email_subject,$email_body,$headers);
return true;
}
}
?>
Change
<form action="form-data/formdata.php" class="form-widget form-control-op-02">
into this
<form action="form-data/formdata.php" method="post" class="form-widget form-control-op-02">
by default HTML form method is get also if i understand correctly you are storing your own Email into input type="hidden you can just store that into a PHP variable for instance $myEmail = "free2rhyme#gmail.com"; so you don't have dangling input type="hidden in your form
Related
I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.
I'm new in this PHP coding stuff.. Once I trigger the Submit button, I got the error of Warning : Invalid argument supplied for foreach() and the email I received it was blank.
Website
HTML Form:
<label>Company Name</label>
<input type="text" class="span12" name="company" id="company2" placeholder="">
PHP code
$mailTo = "$email_address";
$mailSubject = "$email_subject";
$mailBody = "The form values entered by the user are as follows: \n\n";
foreach($HTTP_POST_VARS as $key=>$value)
{
$mailBody .= "$key = $value\n";
}
$mailBody .= "\n\n";
if ($show_ip_address == "on")
{
$mailBody .= "THE IP ADDRESS OF THE FORM USER IS: $REMOTE_ADDR\n\n";
}
if ($show_refering_page == "on")
{
$mailBody .= "THE USER WAS SENT TO THIS SCRIPT FROM THE FOLLOWING FORM: $HTTP_REFERER\n\n";
}
if ($show_browser_type == "on")
{
$mailBody .= "THE USER USED THE FOLLOWING BROWSER TYPE: $HTTP_USER_AGENT\n\n";
}
if ($show_date_and_time == "on")
{
$mailBody .= "THE TIME AND DATE THE FORM WAS COMPLETED: " . date("h:i A l F dS, Y") . "\n\n";
}
$mailBody .= "\nThis message sent via www.BlastMY.com! \n VISIT US AT www.BlastMY.com \n";
$fromHeader = "From: $from_email_name\n";
if(mail($mailTo, $mailSubject, $mailBody, $fromHeader))
{
print ("<B><br></b>");
}
echo "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=$redirect_to_page\">";
?>
Any idea to solve this?
Don't use deprecated syntax, it's really bad. Use:
foreach($_POST as $key=>$value)
simply try this one;
$HTTP_POST_VARS = $_POST
and then,
foreach($_POST as $key=>$value)
Use Like this
foreach($_POST as $key=>$value)
showing the error because $HTTP_POST_VARS has been depricated refer from here
need to replace $HTTP_POST_VARS with $_POST
foreach($_POST as $key=>$val)
{
//code here
}
As everyone else is mentioning, this variable $HTTP_POST_VARS has been deprecated since PHP 4.1.0 and has been replaced by $_POST
This is the official link:
http://php.net/manual/en/reserved.variables.post.php
You can try any of the answers mentioned above and just replace
$HTTP_POST_VARS by $_POST
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.
I am new to PHP and I am trying to create a PHP form field and I have four "Check Boxes" named Output1, Output2, Output3, and Output4 but when I select all four Check Boxes it only send me one and not all four values.
NOTE I have other fields on this from as well but I just wanted to provide you the HTML form info for Output.
Here is the HTML:
<form id="surveyForm" class="form" action="mailsurvey.php" method="post" name="surveyForm" enctype="multipart/form-data" onsubmit="return ValidateContactForm2();">
<input id="Output1" type="checkbox" name="Output1" value="Isolated" />
<input id="Output2" type="checkbox" name="Output2" value="Isolated" />
<input id="Output3" type="checkbox" name="Output3" value="Isolated" />
<input id="Output4" type="checkbox" name="Output4" value="Isolated" />
</form>
PHP Code:
<?php
require("includes/class.phpmailer.php");
require("includes/class.smtp.php");
require("includes/class.pop3.php");
if($_FILES['headshot']['name']!="")
{
$imgtype=explode('.',$_FILES['headshot']['name']);
$len=sizeof($imgtype);
$image_file=uniqid().'.'.$imgtype[$len-1];
$tmppath='uploads/';
move_uploaded_file($_FILES['headshot']['tmp_name'],$tmppath.$image_file);
$file_path=$tmppath.$image_file;
}
else
{
$file_path="";
}
if($_FILES['bodyshot']['name']!="")
{
$imgtype=explode('.',$_FILES['bodyshot']['name']);
$len=sizeof($imgtype);
$image_file=uniqid().'.'.$imgtype[$len-1];
$tmppath='uploads2/';
move_uploaded_file($_FILES['bodyshot']['tmp_name'],$tmppath.$image_file);
$file_path2=$tmppath.$image_file;
}
else
{
$file_path2="";
}
$mail = new PHPMailer();
$mail->Host = "localhost";
$mail->Mailer = "smtp";
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['Comments'];
$totalpower = $_POST['Total_Power']." ".$_POST['Total_Power2']." ".$_POST['Total_Power3']." ".$_POST['Total_Power4']." ".$_POST['Total_Power5'];
$input = $_POST['Input']." ".$_POST['Input2']." ".$_POST['Input3']." ".$_POST['Input4'];
$strings = $_POST['Strings4']." ".$_POST['Strings3']." ".$_POST['Strings2']." ".$_POST['Strings'];
$output = $_POST['Output1']." ".$_POST['Output2']." ".$_POST['Output3']." ".$_POST['Output4'];
$dimming = $_POST['Dimming4']." ".$_POST['Dimming3']." ".$_POST['Dimming2']." ".$_POST['Dimming'];
$packaging = $_POST['Packaging4']." ".$_POST['Packaging3']." ".$_POST['Packaging2']." ".$_POST['Packaging'];
$subject = "New Product Inquiry / Survey";
$body = "Name: " .$name. "<br> ".
"Company: " .$company. "<br>".
"Phone: " .$phone."<br>".
"Email: " .$email."<br><br><hr>".
"Total Power: " .$totalpower."<br>".
"Input: " .$input."<br>".
"Strings: " .$strings."<br>".
"Output: " .$output."<br>".
"Dimming: " .$dimming."<br>".
"Packaging: " .$packaging."<br>".
"Comments: " .$comments."<br>"
;
$mail->IsSMTP();
$mail->From = 'support#domain.com';
$mail->FromName = 'support#domain.com';
$mail->Subject = "New Product Inquiry";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
if($file_path!="")
{
$mail->AddAttachment($file_path);
}
if($file_path2!="")
{
$mail->AddAttachment($file_path2);
}
$mail->MsgHTML($body);
$mail->AddAddress('email#domain.com');
if(!$mail->Send())
{
$msg = "Unable to send email";
}
else
{
$msg = header("location: thank-you2.php");
}
?>
Can someone please tell me why this form will not send ALL Output Fields if a user selects all four boxes. If you have any questions please let me know.
Thanks,
Frank
I figured out what my problem was and the reason why I wanted to post this answer for others to be aware of.
My problem was I was working on the wrong PHP file. I have two of the same PHP files in my site one was burred under a couple folders and one was at the root of the site. The one burred was the one I should have been working on making changes to because that was the LIVE file. While I was uploading a file that wasn't working because it was the wrong one. I figured that out by double check the path in the form element of the form page.
<form id="surveyForm" class="form" **action="subfolder/formmailer_scripts/mailsurvey.php"** method="post" name="surveyForm" enctype="multipart/form-data" onsubmit="return ValidateContactForm2();">
So the morel of the story is pay attention and make sure you don't over look the simple things. I wasted about an hour on this reuploading a file that wasn't were it need to be. Hope this helps others!
I've never done that before and simply need a little advice how to do so …
I have a index.php file with a simple contact form.
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
The index.php file has the following script on top.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address#something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "\n\n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
I have two questions now:
1.)
How exactly can I render/not-render certain stuff when either the validation went wrong or a success or an error comes back when submitting the mail?
e.g. I know that I can do that!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
However $valid will always be wrong on page-load when not submitting the form and also the email will always return the error message on the first page load. How can I only render or not render specific stuff when the form is submitted?
E.g. When submitting the form and a success comes back I don't want to render the #contactform anymore. I simply want to print "Successfully made contact" into an h1 or so.
How can I make that happen? It's probably rather simple I just can't find a solution for myself.
2.)
When using $_SERVER["SCRIPT_NAME"] or PHP_SELF as action the url after submitting the form will always change to "mydomain.com/index.php". Can I prevent that from happening? I want to submit the index.php file itself however I just don't like it when /index.php is written into the url. Is it possible to stop that from happening?
Thank you for your help!
Matt,
For the first question as to printing to the screen based on success or failure of the email, your checks seem fine, but you probably aren't going to get an email failure in time to display that to the screen. That said, you just need to wrap your second set of code in an if statement. Something like this:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
As for not including the directory in the form action, there are many ways to do this, but here's one:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
And then use $script in the form action.