I posted earlier, but have more information so would like to try again. I am trying to help a friend sort out a problem with the contact forms on his web page, which is built using SiteMan. He has a basic 'contact me' form and a 'request a quote' form on his page. The page is meadowwoodpedestals.com and it is hosted on BlueHost. These forms have worked for years, but we have just discovered that he is not receiving messages being sent via these forms. Upon testing, we found that when the submit button is clicked for either of these pages, instead of getting a confirmation screen, a blank screen is displayed and no message is sent. It has been months since he made any changes in the SiteMan editor.
(1) I contacted the host for support, and the reply told me that the errors indicated a problem with the page code for these two pages:
Premature end of script headers: 500.php, referer: http://www.meadowwoodpedestals.com/content/index.php?page=quote
Premature end of script headers: 500.php, referer: http://www.meadowwoodpedestals.com/content/index.php?page=contact
The response said: As you will see, it appears that the issue is with the code itself. You will need to have your web designer, or a script specialist, look over the code for the two pages, in order to resolve these issues. (My Note: the web designer is out of business)
(2) I found the following in the Bluehost forums (this is a bluehost site), I'm not sure if it is relevant?
"The premature end of script header, on a Bluehost server, is more than likely due to CPU quota (or memory?), the script was killed due to resource limitations."
(3) I looked at the page code for the contact form, which uses method="post" action="/cgi-bin/frmctact.php" and all of the basic html looked good - I don't know javascript so I am not sure about this (I've never seen that little cross symbol before?):
<script type="text/javascript" language="javascript">
function m_sfcon (u) {
pre = "mail";
url = pre + "to:" + u;
document.location.href = url + "#meadowwoodpedestals.com";
}†</script>
(4) I looked at the page code for the quote form, which uses method="post" action="/cgi-bin/mail/mail.php", and there are no script tags at all on that page.
(5) Without posting reams of code (as I'm not sure just what is useful), here is my thinking, please let me know if this is a reasonable track:
Since there are two different pages with the same error, I'm thinking it is not really a problem in either quote.php or contact.php
The two forms use different actions, so I'm guessing it is not mail.php or frmctact.php
==> There must be something common between the two pages, but what is it?? maybe index.php?
(6) I looked at index.php, and when I clicked on the opening php tag it closed with a tag in the sixth line of this statement (the ?> just prior to 'si",):
$adress = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
include("data/page_header.php");
switch ($do) {
case "prevphp":
if ($Siteman->mlevel >= 4) {
echo preg_replace("'<\?php.*?\?>'si","",stripslashes($_POST["content"]));
}
break 1;
case "default":
if ($info[2] == 1 || $Siteman->mlevel >= $info[2]) {
include_once($content);
if ($Siteman->mlevel < 5) {
if ($page == "index") {
if (substr_count($_SERVER["HTTP_REFERER"],$adress) == 0) {
echo "<script language=\"Javascript\" type=\"text/javascript\">
var res = screen.width.toString() + 'x' + screen.height.toString();
var referer = '" . urlencode($_SERVER["HTTP_REFERER"]) . "';
document.write('<img width=\"1\" height=\"1\" src=\"stats.php?new=1&res=' + res + '&referer=' + referer + '\" id=\"stat\" name=\"stat\" />');
</script>";
}
}
}
}
break 1;
}
include("data/page_footer.php");
?>
(I don't know why this page works with address misspelled...)
Should I post the full code in cgi-bin/mail/mail.php and cgi-bin/frmctact.php to this area?
My sincere thanks for any / all help!
Abby
EDIT - Here is full frmctact.php - I deleted some blank lines and repeated warnings
<?
// ##########################################################################
//
// DynaForm v1.4 - Created by the Webligo Group
// http://www.webligo.com
//
//--> I deleted license text here
// ###########################################################################
// #### CONFIGURE FROM: ADDRESS ##############################################
// If you would like to specify the From: address of emails sent by DynaForm,
// enter it between the double quotes below. If you leave this blank, the
// server will assign the default email address.
$from_address = "info#meadowwoodpedestals.com";
// ###########################################################################
// #### ACTIVATE REQUIRED FIELDS? ############################################
//
// If you would like to make some fields of your form required, change "no" to
// "yes" below.
$required_on = "yes";
// If you have set $required_on to "yes" above, you can make fields required
// by beginning their name with "r_". For example, if you want to require
// a user to enter their name, use the following HTML:
//
// <input type='text' name='r_Name'>
//
// If a user fails to enter a required field, they will be taken to a page
// where a message such as "You have not completed all the required fields."
// will be displayed. Please specify the URL to this file below:
$required_errorpage = "/content/index.php?page=formerror";
// ###########################################################################
// #### OVERRIDE REQUIRED VARIABLES? #########################################
//NOTE: THIS WILL NOT
// AFFECT YOUR 'TURN ON REQUIRED FIELDS?' SECTION SETTINGS ABOVE.
//
// If you would like to override the three required variables in
// order to hide your email address, email subject, and thank you page
// URL from your email form, change "no" to "yes" below.
$override = "yes";
// If override is set to "yes", the hidden variables on your HTML
// email form named "rec_mailto", "rec_subject", and "rec_thanks" will be
// overridden and can therefore be removed from the form.
// If you have set override to "yes" above, you must specify new values for
// each of these variables below.
// Enter the email address(es) to send the email to.
$incoming_mailto = "info#meadowwoodpedestals.com";
// Enter the email subject.
$incoming_subject = "Website form";
// Enter the thank you page URL.
$incoming_thanks = "/content/index.php?page=formthanks";
// ###########################################################################
// #### BAN IP ADDRESSES? ####################################################
//
// If you would like to ban certain IP addresses from submitting your form,
// change "no" to "yes" below.
$ban_ip_on = "no";
// If you have set $ban_ip_on to "yes" above, please enter a list of the
// IP addresses you would like to ban, seperated only by commas.
// An example has been provided below:
$ban_ip_list = "111.222.33.55,11.33.777.99";
// ###########################################################################
// #### ACTIVATE DOMAIN SECURITY? ############################################
//
// This setting, when set to "yes" (default), will check to make sure other
// people are not submitting data to your dynaform.php file from their
// external domains. This means that if your domain name is "www.mysite.com",
// only forms on "www.mysite.com" will be able to use this dynaform.php.
// IF YOU ARE RECEIVING ERRORS SUCH AS "INVALID DOMAIN" FOR NO REASON, PLEASE
// CHANGE "yes" TO "no" BELOW.
$secure_domain_on = "no";
// ###########################################################################
// #### ACTIVATE AUTO-RESPONSE? ##############################################
//
//
// This setting, when set to "yes", will make DynaForm automatically reply to
// the user who submitted your form with an email message. If you would like
// to use this feature, change "no" to "yes" below.
$autorespond_on = "no";
// If you have set $autorespond_on to "yes" above, you must specify a subject,
// from-address, and message to include in the auto-response email.
// The following setting is the subject of the auto-response email:
$autorespond_subject = "Your Form Submission";
// The following setting is the from-address of the auto-respond email:
$autorespond_from = "youremail#yoursite.com";
// The following setting is the message of your auto-response email:
$autorespond_contents = "Your submission from our website has been received. Thank you!";
// DynaForm also needs to know how to retrieve the user's email address.
// You must specify the name of the field into which the user will enter
// their email address. For example, if your email form contains an input
// field like "<input type='text' name='Email'>" you would set the
// following setting to "Email".
$autorespond_mailto_field = "Email";
// ###########################################################################
// MAKE SURE DYNAFORM IS NOT BEING LOADED FROM THE URL
if($HTTP_SERVER_VARS['REQUEST_METHOD'] == "GET") {
echo "
<html>
<head><title>Webligo PHP DynaForm is installed correctly.</title></head>
<body>
<font style='font-family: verdana, arial; font-size: 9pt;'>
<b>DynaForm is installed correctly.</b></font><br>
<font style='font-family: verdana, arial; font-size: 8pt;'>
DynaForm Easy PHP Form Mailer was created by <a href='http://www.webligo.com'>Webligo Developments</a>.
</font>
</body></html>
";
exit();
}
// SET VARIABLES
$incoming_fields = array_keys($HTTP_POST_VARS);
$incoming_values = array_values($HTTP_POST_VARS);
if($override == "no") {
$incoming_mailto = #$HTTP_POST_VARS['rec_mailto'];
$incoming_subject = #$HTTP_POST_VARS['rec_subject'];
$incoming_thanks = #$HTTP_POST_VARS['rec_thanks'];
}
$incoming_mailto_cc = #$HTTP_POST_VARS['opt_mailto_cc'];
$incoming_mailto_bcc = #$HTTP_POST_VARS['opt_mailto_bcc'];
$form_url = #$HTTP_REFERER;
// MAKE SURE DYNAFORM IS BEING RUN FROM THE RIGHT DOMAIN
if($secure_domain_on == "yes") {
$form_url_array = parse_url($form_url);
$form_domain = $form_url_array[host];
if($form_domain != $HTTP_SERVER_VARS[HTTP_HOST]) {
echo "<h2>DynaForm Error - Invalid Domain</h2>
You have accessed DynaForm from an external domain - this is not allowed.<br>
You may only submit forms to a DynaForm file that exists on the same domain name.<br>
If you believe to be receiving this message in error, please refer to your readme.txt file.
<br><br>";
$error = "yes";
}
}
// CHECK IF MAILTO IS SET
if($incoming_mailto == "") {
echo "<h2>DynaForm Error - Missing Field</h2>
Your form located at <a href='$form_url'>$form_url</a> does not work because you forgot to include
the required \"<b>rec_mailto</b>\" field within the form. This field specifies who the email will
be sent to.
<br><br>
This should look like:<br>
<input type=\"hidden\" name=\"rec_mailto\" value=\"youremail#yoursite.com\">
<br><br>
If you are still confused, please refer to the readme.txt for more information and examples.<br><br><br><br>
";
$error = "yes";
}
// CHECK IF SUBJECT IS SET
if($incoming_subject == "") {
echo "<h2>DynaForm Error - Missing Field</h2>
Your form located at <a href='$form_url'>$form_url</a> does not work because you forgot to include
the required \"<b>rec_subject</b>\" field within the form. This field specifies the subject of
the email that will be sent.
<br><br>
This should look like:<br>
<input type=\"hidden\" name=\"rec_subject\" value=\"New DynaForm Email\">
<br><br>
If you are still confused, please refer to the readme.txt for more information and examples.<br><br><br><br>
";
$error = "yes";
}
// CHECK IF THANKS IS SET
if($incoming_thanks == "") {
echo "<h2>DynaForm Error - Missing Field</h2>
Your form located at <a href='$form_url'>$form_url</a> does not work because you forgot to include
the required \"<b>rec_thanks</b>\" field within the form. This field specifies what page the user
will be taken to after they submit the form.
<br><br>
This should look like:<br>
<input type=\"hidden\" name=\"rec_thanks\" value=\"thanks.html\">
<br><br>
If you are still confused, please refer to the readme.txt for more information and examples.<br><br><br><br>
";
$error = "yes";
}
// CHECK IF IP ADDRESS IS BANNED
if($ban_ip_on == "yes") {
if(strstr($ban_ip_list, $HTTP_SERVER_VARS[REMOTE_ADDR])) {
echo "<h2>DynaForm Error - Banned IP</h2>
You cannot use this form because your IP address has been banned by the administrator.<br>
";
$error = "yes";
}
}
if($error == "yes") {
exit();
}
// SET EMAIL INTRODUCTION
$message = "This email was received from your DynaForm located at $form_url \n\n";
// LOAD EMAIL CONTENTS
for ($i = 0; $i < count($incoming_fields); $i++) {
if($incoming_fields[$i] != "rec_mailto") {
if($incoming_fields[$i] != "rec_subject") {
if($incoming_fields[$i] != "rec_thanks") {
if($incoming_fields[$i] != "opt_mailto_cc") {
if($incoming_fields[$i] != "opt_mailto_bcc") {
// CHECK FOR REQUIRED FIELDS IF ACTIVATED
if($required_on == "yes") {
$sub = substr($incoming_fields[$i], 0, 2);
if($sub == "r_") {
if($incoming_values[$i] == "" OR !isset($incoming_values[$i]) OR $incoming_values[$i] == " ") {
header("Location: $required_errorpage");
exit();
}}}
// ADD FIELD TO OUTGOING MESSAGE
$message .= "$incoming_fields[$i]:\n$incoming_values[$i]\n\n";
}}}}}}
// SET EMAIL FOOTER
$message .= "\n\nEnd";
// CLEAR HEADERS
$headers = "";
// ADD FROM ADDRESS
if($from_address != "") {
$headers .= "From: $from_address\r\n";
}
// CHECK FOR CC OR BCC
if($incoming_mailto_cc != "") {
$headers .= "Cc: $incoming_mailto_cc\r\n";
}
if($incoming_mailto_bcc != "") {
$headers .= "Bcc: $incoming_mailto_bcc\r\n";
}
// SEND EMAIL
mail($incoming_mailto, $incoming_subject, $message, $headers);
// SEND AUTO-RESPONSE IF ACTIVATED
if($autorespond_on == "yes") {
$autorespond_mailto = #$HTTP_POST_VARS[$autorespond_mailto_field];
$autorespond_headers = "From: $autorespond_from";
mail($autorespond_mailto, $autorespond_subject, $autorespond_contents, $autorespond_headers);
}
// FORWARD TO THANK YOU PAGE
header("Location: $incoming_thanks");
?>
The 500 errors mean PHP is crashing. You need to look in the apache error log (bluehost have an icon for this in the cpanel, IIRC), and hopefully will see some PHP error message.
[people say] "the script was killed due to resource limitations."
I don't think it is this, because the 500 error happens immediately after submitting the form.
Related
At this moment I have a small contact-box on my page that ask for telephone number.
If no number is entered the form should do nothing. Instead of sending a empty email to my client.
It is not necessary that the form creates a message or something else if the field is empty.
I just want to have extra php code, that makes sure nothings happening if somebody clicks the send button while the field is left empty.
This is my code:
<?php
$EmailFrom = Trim(stripslashes($_POST['email']));
$EmailTo = "INFO#EPIMMO.BE";
$Subject = "Vraagt om hem te bellen - Website Epimmo";
$free = Trim(stripslashes($_POST['free']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Volgend telefoonnummer werd ingevoerd via uw website:";
$Body .= $free;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.epimmo.be/hire-us-phone.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
Thanks for reading and a hopefully a solution ;-)
Kristof
First you can add if condition that will check email or phone number is not blank
and in its not blank then execute next code of sending an email.
if(isset($_POST['email']) && $_POST['email']!="")
{
//write here your code to send an email
}
You can do this with HTML like this:
<input type="number" required></input>
Just after <?php you could add the following code:
if(!isset($_POST['free']) || empty($_POST['free']) {
header('location: /hire-us-phone.php');
exit;
}
header('location: /hire-us-phone.php'); will do a header redirect to /hire-us-phone.php (which is much better than using a meta refresh) and exit; will ensure no code after the header redirect will be run.
To redirect, you should be using:
header("Location: your-url.php");
exit;
This code would need to go before anything is echoed, including whitespace.
Also, what is this code?
// validation
$validationOK=true;
if (!$validationOK) {
Clearly, the if statement will never be false.
You could validate the easy way, such as one big if statement. But a better way is to do something like this:
if($_POST['email'] == ''){
$_SESSION['my_form']['errors']['email'] = 'The email was left blank';
}
if(!empty($_SESSION['my_form']['errors'])){
// redirect & exit here
}
And then on your form page, you can use this session data to display a relevant error to the user:
if(isset($_SESSION['my_form']['errors']['email'])){
// output $_SESSION['my_form']['errors']['email'] here to the user
}
Here, we're presented with the action page, which means something has already happened: The form was submitted, and redirected to the action page.
As #Mohini pointed out, you can test the condition of an empty field on the action page.
But after the submit button is pressed, you can easily use javascript on the form page to test if the required fields are populated.
(plain vanilla javascript)
if(! document.forms['formname']['email'].value == "" ){
document.forms['formname'].sumit();
} else {
// do nohing. Or do something. I don't really care!
}
I am using a form to get newsletter sign ups on my website. I am using a contact.php file which works well but there is no validation so I occasionaly and sometimes frequently get blank responses.
I'm not sure why this is, but I believe I need validation.
This is my original code
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and this is the code I tried to add to validate but it doesnt work.
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "jcash1#gmail.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
/* Validation */
$error=0; // check up variable
$errormsg = '<ul class="errorlist">';
/* get it checking */
if(!check_email($email))
{
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
}
$errormsg .= '</ul>';
if($error == 0) {
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo 'error|'. $errormsg;
}
?>
Can anyone offer some insight?
I cannot for the life of me get this to work...
I am getting an Error with the plugin and I have loaded it correctly
so I tried adding this :
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
like so:
<?php
/*
Author: Andrew Walsh
Date: 30/05/2006
Codewalkers_Username: Andrew
This script is a basic contact form which uses AJAX to pass the information to php, thus making the page appear to work without any refreshing or page loading time.
*/
$to = "hello#interzonestudio.com"; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
/* Now lets trim up the input before sending it */
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
} else {
echo("$email is not a valid email address");
}
?>
Which is not working. I think it is beauce I have implemented the code in the wrong place but I am not sure. Any help would be greatly appreciated.
You can use filter_var() function in PHP for validating email addresses.
For simply validating email addresses in PHP you can use it like this,
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Valid email";
}
And your code can be improved like this.
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|Thank you. We promise you won’t regret it.'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
}
else {
$errormsg.= "<li class='errormessage'>ERROR: not a valid email.</li>";
$error++;
echo '</ul> error|'. $errormsg;
}
If you want to know more about it, visit official PHP documentation page here : http://php.net/manual/en/filter.filters.validate.php
Or use jquery validation plugin. I highly recommend it.
Code will look similar to below
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
You can use server side validation by using this code
if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
//your email sending code here
} else {
echo("$email is not a valid email address");
}
I am adding a contact page to my website, but having issues with the comment text box. When the user enters invalid information into the name and email text field, the website redirects the user back to the contact page to fill out the correct information. However, I want the comment box to be optional for the user. For example, the user will enter their name and email, but doesn't have any comments. The code should then process the information. Currently, my code will redirect the user back to the contact page because the user did not enter any information into the comment box. Any suggestions on how to fix this error?
Thanks!
if (empty($_REQUEST['comment'])) {
$error = TRUE;
} else {
$comment = $_REQUEST['comment'];
$form['comment'] = $comment;
if (!preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
}
If you want to allow the content box to be empty, just let an empty value be an acceptable value. This means only running your validation against that field if there is a value present. This means removing your if/else statement since empty($_REQUEST['comment']) is no longer a valid check.
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
I just added !empty($comment) && to your check which basically says, "if there is a value go ahead and validate it".
One thing you should also do if you use this code is trim whitespace from your comment box values. Otherwise a user could type a space character and that would not be considered empty:
$comment = trim($_REQUEST['comment']);
Final code:
$comment = trim($_REQUEST['comment']);
$form['comment'] = $comment; // I am assuming this is used elsewhere
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
I've finally got this PHP email script working (didn't work on localhost…), but my concern is that it's not safe.
So - is this safe for spamming and any other security pitfalls I'm not aware of?
<?php
$email = 'notification#domain.com';
$subject = 'Notify about stuff';
$notify = $_REQUEST['email'];
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $notify)) {
echo "<h4>Your email address doesn't validate, please check that you typed it correct.</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
elseif(mail($email, $subject, $notify)) {
echo "<h4>Thank you, you will be notified.</h4>";
} else {
echo "<h4>Sorry, your email didn't get registered.</h4>";
}
?>
Unrelated: is there a PHP function I can use instead of javascript:history.back(1) ?
Edit: the script using filter instead of RegEx
<?php
$email = 'notification#domain.com';
$subject = 'Notify about stuff';
$notify = $_REQUEST['email'];
if (!filter_var($notify, FILTER_VALIDATE_EMAIL)) {
echo "<h4>This email address ($notify) is not considered valid, please check that you typed it correct.</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
elseif(mail($email, $subject, $notify)) {
echo "<h4>Thank you, you will be notified.</h4>";
} else {
echo "<h4>Sorry, your email didn't get registered.</h4>";
}
?>
I don't know if id use $_SERVER['HTTP_REFERER'] to go back. I feel like that could leave you open to attack since it's set via the request. The way to do it would be to use sessions on the previous page. This way you're not dumping untrustworthy data onto your site.
I dont see any security risks, but id like to suggest the use of filter when checking the validity of emails. its much easier than messing with REs.
You can't just regexp match an email address against a short regexp pattern if you want to accept all validly formed email addresses and reject all non-valid one. Use a parser (1, 2) that actually implement against the relevant RFCs to check for validity.
Other things you can do is checking HTTP_REFERER to make sure the request came from within your domain as Chacha102 already mentioned. Just note that not all agent send HTTP_REFERER, and that it can be optionally turned off or faked by users.
If you want to go the extra mile to make sure they are giving you a valid email address, you can check for existing DNS record for mail servers at the domain specified (A, MX, or AAAA). And on top of that, you can do callback verification. That's where you connect to the mail server, tell it you want to send to this email address and see if they say OK.
For callback verification, you should note greylisting servers say OK to everything so even that is not a guarantee. Here's some code I used when I needed such a script. It's a patch onto the parser from (1).
#
# Email callback verification
# Based on http://uk2.php.net/manual/en/function.getmxrr.php
#
if (strlen($bits['domain-literal'])){
$records = array($bits['domain-literal']);
}elseif (!getmxrr($bits['domain'], $mx_records, $mx_weight)){
$records = array($bits['domain']);
}else{
$mxs = array();
for ($i = 0; $i < count($mx_records); $i++){
$mxs[$mx_records[$i]] = $mx_weight[$i];
}
asort($mxs);
$records = array_keys($mxs);
}
$user_okay = false;
for ($j = 0; $j < count($records) && !$user_okay; $j++){
$fp = #fsockopen($records[$j], 25, $errno, $errstr, 2);
if($fp){
$ms_resp = "";
$ms_resp .= send_command($fp, "HELO ******.com");
$ms_resp .= send_command($fp, "MAIL FROM:<>");
$rcpt_text = send_command($fp, "RCPT TO:<" . $email . ">");
$ms_resp .= $rcpt_text;
$ms_code = intval(substr($rcpt_text, 0, 3));
if ($ms_code == 250 || $ms_code == 451){ // Accept all user account on greylisting server
$user_okay = true;
}
$ms_resp .= send_command($fp, "QUIT");
fclose($fp);
}
}
return $user_okay ? 1 : 0;
I'm trying to make a div fade out with jquery after the form validates the user input after pushing submit. I'm trying to avoid the form from fading out before it validates in case the user didn't enter the correct information.
I would like to know if I can just add script tags in between my php tags, so that once the validation finishes, I just run the javascript real quick and then pick up with the rest of the php, like so:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
$site_owners_email = 'zeckdude#gmail.com'; // Replace this with your own email address
$site_owners_name = 'Chris Seckler'; // replace with your name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address";
}
if (strlen($comments) < 3) {
$error['comments'] = "Please leave a comment.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Website Contact Form";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->AddAddress('zeckdude#gmail.com', 'Chris Seckler');
$mail->Body = $comments;
$mail->Send();
?>
<script type="text/javascript">
$(function(){
$('#container').fadeOut(1000);
});
</script>
<?php
echo "<li class='success'> Congratulations, " . $name . ". We've received your email. We'll be in touch as soon as we possibly can! </li>";
echo nl2br("<b>Message Sent:</b>
From: $name
Email: $email
Message: $comments
<br/><a href='http://www.google.com'>Link</a>");
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['comments'])) ? "<li>" . $error['comments'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
Yes, but your result will not be what you intend.
PHP is all executed prior to the document being sent to the client (user). Javascript is executed after the document has been received by the client.
Less related comments:
Your script is vulnerable to Cross Site Scripting (XSS) through POST. Do not use it on a real site before you address this issue.
One way you can accomplish what you may be intending to do is to have the second part of your php code render the html content within a div that is hidden <div id='content' style="display:none">...other content...</div>. Then, in javascript after the fade is complete, use javascript clear the display:none attribute from the div to make it appear.
Good luck!
Why not try it? You already have the code written. From what I see in your code, you should be able to do this without a problem.
No that certainly won't work the way you want - your php script does not have that sort of intimate interaction with the browser and cannot come back and make an existing form do something else in this fashion. Once php starts producing output and sends the page header, it's a brand new web page you can't just make the old one go away.
you should probably consider looking at jquery forms plugin. you could then submit your form using ajax, and leave the active form visible. Once you've had a successful return from your ajax submit, then fade the form and move on to the next thing
I actually just tried the code that I showed you above and it works pretty well. At least it looks good. Here's it is live: Example Form
What I'm trying to do now is to get the Message that echo's in at the end to actually fade in instead of just pop in.
I think that George Deglin's answer,
have the second part of your php code
render the html content within a div
that is hidden.
<div id='content' style="display:none">
...other content...
</div>
Then, in javascript
after the fade is complete, use
javascript clear the display:none
attribute from the div to make it
appear.
would most likely work for that.