php simple Contact form re-submitting on Refresh of browser - javascript

The following form works as intended, including the honeypot, but if someone clicks on Refresh in the browser prior to finishing the form, it tries to resubmit. I have tried sessions but it is not working. Does anyone know how I can make the page redirect back to contact.php or end the session so it does not resubmit on refresh in the browser? ( I have spent 2 days searching for answers ). Thanks
Code:
<!--form-->
<?php
//fields
$link_address = 'contact.php'; // page to redirect to home page
$honeypot = '';
$error = '';
$name = 'Name (required)';
$email = 'Email (required)';
$comments = 'Message (required)';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['honeypot'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name (required)') {
$error = '<div class="error_message">Please enter your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Please enter your Name</div>';
} else if(trim($email) == 'Email (required)') {
$error = '<div class="error_message">Please enter an email address</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Please enter an email address</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Please enter a valid email address</div>';
} else if(trim($comments) == 'Message (required)') {
$error = '<div class="error_message">Please enter a Message</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">Please enter a Message</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "email#youremail.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='success_page'>";
echo "<div id='thanks'>";
echo "<h1>Message Sent Successfully.</h1>";
echo "<p id='cprint1'>Thank you. Your message was sent to us. </br>We will be in touch shortly.</p>";
echo "<p id='print'><a href='javascript:window.print()'>Print your Message</a></p>";
echo "<p id='cclose'><a href='$link_address'>Close this Message</a></p>";
echo "</div>";
echo "<div id='thanks2'>";
echo "<div id='titlemsg'>Below is your message</div>";
echo "<p><span>Name:</span> $name</p>";
echo "<p><span>Email:</span> $email</p>";
echo "<p><span>Message:</span>$comments</p>";
echo "</div>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<!--form-->
<form method="post" action="" id="myform" autocomplete="off">
<div id="error"><?php echo $error; ?></div>
<input name="name" type="text" id="name" class="form1"
value="<?php echo $name; ?>" onfocus="if(this.value == 'Name (required)') {this.value = ''; }" onblur="if(this.value == '') { this.value = 'Name (required)'; }" value="Name (required)" />
<input name="email" type="text" id="email" class="form1"
value="<?php echo $email; ?>" onfocus="if(this.value == 'Email (required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Email (required)'; }" value="Email (required)" />
<input name="honeypot" type="text" id="honeypot" class="form2" value="<?php echo $honeypot; ?>" />
<textarea name="comments" cols="40" rows="3" id="comments"
value="<?php echo $comments; ?>" onfocus="if(this.value == 'Message (required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Message (required)'; }" value="Message (required)"><?php echo $comments; ?></textarea>
<input name="contactus" type="submit" class="submit" id="contactus" value="Contact us" />
</form>
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>

You can save your message in session on successfull mail sent. and then refresh your page and check if session exist then show message and reset session.
Just redirect it to the same page after making the use of form data.
Example-
header('location:yourpage.php');
and you can also unset $_POST after inserting it to Database.
unset($_POST);

You can use the javascript redirect:
<script>
window.location.href = 'test.php';
</script>

Related

Display Popup Message in Same Page, for HTML Contact Form by PHP

I have a contact form on my index.html that works with a contact.php file. I need to display a popup message after submitting the form for "message sent" or "something went wrong" without leaving the index.html. Currently, it displays the message in a popup on a blank page.
I truly tried to solve it and I checked a lot of similar questions here, truth is i'm new to php and js (I'm like Jon Snow, I know nothing) and I just couldn't figure out a solution for my case.
I appreciate any help :)
*PHP code:
<?php
if($_POST) {
$visitor_name = "";
$visitor_email = "";
$email_title = "";
$concerned_department = "";
$visitor_message = "";
$email_body = "<div>";
if(isset($_POST['visitor_name'])) {
$visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Visitor Name:</b></label> <span>".$visitor_name."</span>
</div>";
}
if(isset($_POST['visitor_email'])) {
$visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']);
$visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL);
$email_body .= "<div>
<label><b>Visitor Email:</b></label> <span>".$visitor_email."</span>
</div>";
}
if(isset($_POST['email_title'])) {
$email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Reason For Contacting Us:</b></label> <span>".$email_title."</span>
</div>";
}
if(isset($_POST['concerned_department'])) {
$concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Concerned Department:</b></label> <span>".$concerned_department."</span>
</div>";
}
if(isset($_POST['visitor_message'])) {
$visitor_message = htmlspecialchars($_POST['visitor_message']);
$email_body .= "<div>
<label><b>Visitor Message:</b></label>
<div>".$visitor_message."</div>
</div>";
}
if($concerned_department == "billing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "marketing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "technical support") {
$recipient = "test#mail.com";
}
else {
$recipient = "test#mail.com";
}
$email_body .= "</div>";
$headers = 'MIME-Version: 1.0' . "\r\n"
.'Content-type: text/html; charset=utf-8' . "\r\n"
.'From: ' . $visitor_email . "\r\n";
if(mail($recipient, $email_title, $email_body, $headers)) {
echo '<script type="text/javascript"> window.onload = function(){
alert("Thank you for contacting us. You will get a reply as soon as possible.");
}</script>';
} else {
echo '<script type="text/javascript"> window.onload = function(){
alert("We are sorry but the email did not go through.");
}</script>';
}
} else {
echo '<script>alert("Something went wrong.")</script>';
}
?>
*HTML code:
<div class="form">
<form action="/php/contact.php" method="post">
<div class="elem-group">
<input type="text" id="name" name="visitor_name" placeholder="Your Name" pattern=[A-Z\sa-z]{3,20} required>
</div>
<div class="elem-group">
<input type="email" id="email" name="visitor_email" placeholder="Your E-mail" required>
</div>
<div class="elem-group">
<input type="text" id="title" name="email_title" required placeholder="Reason For Contacting Us" pattern=[A-Za-z0-9\s]{8,60}>
</div>
<div class="elem-group">
<textarea id="message" name="visitor_message" placeholder="Your Message" required></textarea>
</div>
<button type="submit" class="button white">Send Message</button>
</form>
</div>
Thank you!!
In my opinion, the best way is to use AJAX. My proposition is to create a JS sript that is collecting data and executing php code.
Small change in html:
<div class="form">
<div class="elem-group">
<input type="text" id="name" name="visitor_name" placeholder="Your Name" pattern=[A-Z\sa-z]{3,20} required>
</div>
<div class="elem-group">
<input type="email" id="email" name="visitor_email" placeholder="Your E-mail" required>
</div>
<div class="elem-group">
<input type="text" id="title" name="email_title" required placeholder="Reason For Contacting Us" pattern=[A-Za-z0-9\s]{8,60}>
</div>
<div class="elem-group">
<textarea id="message" name="visitor_message" placeholder="Your Message" required></textarea>
</div>
<button id="contact_submit" type="submit" class="button white">Send Message</button>
</div>
In fact you already has IDs of inputs, creating user side code should be very easy in jQuery:
$("#contact_submit").click(function(){
//Collecting data
let name = $("#name").val();
let email = $("#email").val();
let title = $("#title").val();
let message = $("#message").val();
//AJAX sending data to php code
$.post("/php/contact.php",
{
visitor_name: name,
visitor_email: email,
email_title: title,
visitor_message: message,
},
function(response){
//Response from PHP in alert
//for example: if You use echo "Something went wrong" the message in alert will be the same.
alert(response);
}
);
});
The only thing i would change in PHP is response:
<?php
if($_POST) {
$visitor_name = "";
$visitor_email = "";
$email_title = "";
$concerned_department = "";
$visitor_message = "";
$email_body = "<div>";
if(isset($_POST['visitor_name'])) {
$visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Visitor Name:</b></label> <span>".$visitor_name."</span>
</div>";
}
if(isset($_POST['visitor_email'])) {
$visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']);
$visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL);
$email_body .= "<div>
<label><b>Visitor Email:</b></label> <span>".$visitor_email."</span>
</div>";
}
if(isset($_POST['email_title'])) {
$email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Reason For Contacting Us:</b></label> <span>".$email_title."</span>
</div>";
}
if(isset($_POST['concerned_department'])) {
$concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING);
$email_body .= "<div>
<label><b>Concerned Department:</b></label> <span>".$concerned_department."</span>
</div>";
}
if(isset($_POST['visitor_message'])) {
$visitor_message = htmlspecialchars($_POST['visitor_message']);
$email_body .= "<div>
<label><b>Visitor Message:</b></label>
<div>".$visitor_message."</div>
</div>";
}
if($concerned_department == "billing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "marketing") {
$recipient = "test#mail.com";
}
else if($concerned_department == "technical support") {
$recipient = "test#mail.com";
}
else {
$recipient = "test#mail.com";
}
$email_body .= "</div>";
$headers = 'MIME-Version: 1.0' . "\r\n"
.'Content-type: text/html; charset=utf-8' . "\r\n"
.'From: ' . $visitor_email . "\r\n";
if(mail($recipient, $email_title, $email_body, $headers)) {
echo 'Thank you for contacting us. You will get a reply as soon as possible.';
} else {
echo 'We are sorry but the email did not go through.';
}
} else {
echo 'Something went wrong.';
}
?>
And it should work, Only thing i could not find was "concerned_department" but i hope you will be albe to add it by yourself. In case you would have problem with it, let me know.
I would give an suggestion to use an alert box as an popup. The code for the same is :
Example:
Add this to your file where you are checking the logic :
if (move_uploaded_file($file, $destination)) {
$sql = "INSERT INTO files (pdf_file) VALUES ('$filename')";
if (mysqli_query($conn, $sql)) {
header("location:form5.php?upload=success");
}
} else {
header("location:form5.php?upload=notsuccess");
}
}
And now add this to your main file :
<?php
if (isset($_GET['upload'])) {
if ($_GET['upload'] == 'success') {
echo '<script>alert("Data added Successfully")</script>';
}
if ($_GET['upload'] == 'notsuccess') {
echo '<script>alert("Data Not added")</script>';
}
}
?>
This will give you an Alert box if the event is successful or unsuccessful stating the same.

PHP,jQuery,HTML form with ajax is not working

I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax
From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH

need to add smtp to the jquery form

this form is sending data to database but i need the query should also go to the two other ids someone said use smtp but i don't know how and where to add smtp in this form. please help thanks in advance
<?php
// Attention! Please read the following.
// It is important you do not edit pieces of code that aren't tagged as a configurable options identified by the following:
// Configuration option.
// Each option that is easily editable has a modified example given.
$error = '';
$name = '';
$email = '';
$organisation = '';
$phone = '';
$subject = '';
$comments = '';
//$verify = '';
if(isset($_POST['contactus'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$organisation = $_POST['name'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
//$verify = $_POST['verify'];
$servername = "localhost";
$username = "auweb";
$password = "auw3b";
$dbname = "auweb";
$useragent=$_SERVER['HTTP_USER_AGENT'];
$ip=$_SERVER['REMOTE_ADDR'];
//echo $msg;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
}
$sql="";
if(empty($name)||empty($phone)||empty($email)||empty($subject)||empty($comments)){
$sql = "INSERT INTO `aki_logs` (`ts`, `name`, `email`, `phone`, `state`, `course`, `useragent`, `ip`, `status`)VALUES (now(), '$name', '$email', '$phone', '$comments', '$subject', '$useragent', '$ip', 'Error');";
//echo 'Please enter all the data';
header('location:index.php');
}
else{
$sql = "INSERT INTO `aki_logs` (`ts`, `name`, `email`, `phone`, `state`, `course`, `useragent`, `ip`, `status`)VALUES (now(), '$name', '$email', '$phone', '$comments', '$subject', '$useragent', '$ip', 'Success');";
}
$conn->query($sql);
$conn->close();
//$to="admissions2#ansaluniversity.edu.in,siddhartha#digidarts.com";
//$to='admissions2#ansaluniversity.edu.in';
#date_default_timezone_set('Asia/Kolkata');
#session_start();
unset($_POST['formname']); unset($_POST['submit']);
$csv = implode('","', $_POST);
$csv = '"'.date("d-m-Y").'","'. date("H:i:s") .'","' . $csv . '"' . "\r\n";
$file = '../../data/'. basename( __DIR__ ) .'.csv';
#file_put_contents($file, $csv, FILE_APPEND);
// Configuration option.
// You may change the error messages below.
// e.g. $error = 'Attention! This is a customised error message!';
if(trim($name) == '') {
$error = '<div class="error_message">Attention! You must enter your name.</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Attention! Please enter a valid email address.</div>';
// Configuration option.
// Remove the // tags below to active phone number.
} else if(!is_numeric($phone)) {
// $error = '<div class="error_message">Attention! Phone number can only contain digits.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
}
if(trim($organisation) == '') {
$error = '<div class="error_message">Attention! Please enter a subject.</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">Attention! Please enter your message.</div>';
}// else if(trim($verify) == '') {
// $error = '<div class="error_message">Attention! Please enter the verification number.</div>';
//} else if(trim($verify) != '4') {
// $error = '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
//}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "";
$address = "mk#gmail.com, mk2#gmail.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_organisation = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $organisation, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
// Configuration option.
// RIf you active phone number, swap the tags of $e-reply below to include phone number.
$e_reply = "You can contact $name via email, $email or via phone $phone";
//$e_reply = "You can contact $name via email, $email";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_organisation, $msg, "From: 'enquiry#gmail.com'\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
// Email has sent successfully, echo a success page.
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php echo $error; ?>
<fieldset>
<legend>Please fill in the following form to contact us</legend>
<form method="post" action="#succsess_page">
<div class="row">
<div class="col-md-6">
<label for=name accesskey=U><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="<?php echo $name; ?>" />
<br />
<label for=email accesskey=E><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="<?php echo $email; ?>" />
<br />
<label for=phone accesskey=P><span class="required">*</span> Phone</label>
<input name="phone" type="text" id="phone" size="30" value="<?php echo $phone; ?>" />
</div><!--COL-FORM HALF-->
<div class="col-md-6">
<label for=subject accesskey=S><span class="required">*</span> Subject</label>
<select name="subject" id="subject">
<option value="B. A. (Hons) - Liberal Arts">B. A. (Hons) - Liberal Arts</option>
</select>
<br />
<label for=comments accesskey=C><span class="required">*</span> Query</label>
<textarea name="comments" cols="30" rows="3" id="comments"><?php echo $comments; ?></textarea>
<hr />
<!--<p><span class="required">*</span> Are you human?</p>
<label for=verify accesskey=V> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="<?php echo $verify; ?>" /><br /><br />-->
<input name="contactus" type="submit" class="submit" id="contactus" value="Submit" />
</div>
</div>
</form>
</fieldset>
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
?>
If you should send an email after form submitting, you can use the php "mail()" function (http://php.net/manual/en/function.mail.php).
Or, if you wanna use SMTP protocol you should integrate in your project a plugins like PHPMailer. See ya!

PHP - MySQL - Sign Up Trouble [blank data]

I've a website since 2013. I've signed up quite 12k users. From 5 months I have noticed some blank users. They receive a user-code but "name" "surname" and "email" fields are blanks.
This event happen every 50/100 users registrations. Why? I have tried everything, but in all test I can't sign up without data. Also other people that have made tests can't sign up without insert data.
This is the form:
<form action="script/****.php" method="post" onsubmit="return validate()">
<label for="name">Name</label>
<input type="text" id="name" name="name" <?php if($_REQUEST['name'] != "") echo "value='".$_REQUEST['name']."'"; ?> />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" <?php if($_REQUEST['surname'] != "") echo "value='".$_REQUEST['surname']."'"; ?> />
<label for="email">Email</label>
<input type="email" id="email" name="email" <?php if($_REQUEST['email'] != "") echo "value='".$_REQUEST['email']."'"; ?> />
<label for="c_email">Retype Email</label>
<input type="email" id="c_email" name="c_email" />
<label for="password">Password</label>
<input type="password" id="password" name="password" />
<label for="c_password">Retype Password</label>
<input type="password" id="c_password" name="c_password" />
<input type="submit" value="registrati" />
</form>
This is the code that stores data on db:
<?php
function mt_rand_str ($length, $available = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789') {
for ($string = '', $i = 0; $i < $length; ++$i) {
$string .= $available[mt_rand(0, strlen($available)-1)];
}
return $string;
}
include('connection.php');
$con = connection();
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$bonus = 10;
$today = new DateTime();
$signUpDate = $today->format('Y-m-d');
if(strpos($name,' ') !== false) {
echo "
<script>
alert('Nome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($surname,' ') !== false) {
echo "
<script>
alert('Cognome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($email,' ') !== false) {
echo "
<script>
alert('Email non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($password,' ') !== false) {
echo "
<script>
alert('Password non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
connectionCheck($con);
userDbCheck($con);
$checkEmail = mysqli_query($con,"Select * from Users_DB where email = '$email'");
if(!mysqli_fetch_assoc($checkEmail)) {
do {
$userCode = mt_rand_str(8);
}
while(mysqli_fetch_assoc(mysqli_query($con,"select * from Users_DB where binary UserCode = '$userCode'")));
$value = 20;
mysqli_query($con,"Insert into User_DB (UserCode,Name,Surname,Phone,Email,Password,SignUpDate,bonus)
values ('$userCode','$name','$surname','','$email','$password','$signUpDate','$bonus')");
}
else {
echo "
<script>
alert('Email exists already!');
window.location.href = '../signup.php';
</script>";
}
?>
I hope you can find what I have not. As you can see, I've put in php code some data check too.
So I have
1) HTML5 check: type="email". I'm thinking to put also "pattern match" in all fields
2) JavaScript check
3) PHP check
I'm so desperate...
Thank you before.

php Send mail not working in wordpress

I have a contact form where the user inputs his name, designation, message etc and is validated using a javascript file called screen.js.
This is my code in the contact form in html view.
<div class="contact_us">
<form id="contactform" action="#" method="post">
<div class="formpart">
<label for="contact_name">Name</label>
<p><input type="text" name="name" id="contact_name" value="" class="requiredfield"/></p>
</div>
<div class="formpart formpart1">
<label for="contact_designation">Designation</label>
<p><input type="text" name="designation" id="contact_designation" value=""/></p>
</div>
<div class="formpart">
<label for="contact_companyname">Company Name</label>
<p><input type="text" name="companyname" id="contact_companyname" value="" class="requiredfield"/></p>
</div>
<div class="formpart formpart1">
<label for="contact_email">Email Address</label>
<p><input type="text" name="email" id="contact_email" value="" class="requiredfield"/></p>
</div>
<div class="formpart">
<label for="contact_phone">Contact No.</label>
<p><input type="text" name="phone" id="contact_phone" value=""/></p>
</div>
<div class="formpart">
<label for="contact_message">Message</label>
<p><textarea name="message" id="contact_message" class="requiredfield"></textarea></p>
</div>
<div class="formpart">
<button type="submit" name="send" class="sendmessage">Send</button>
</div>
<div class="formpart">
<span class="errormessage">Error! Please correct marked fields.</span>
<span class="successmessage">Email send successfully!</span>
<span class="sendingmessage">Sending...</span>
</div>
</form>
</div>
and the javascript file screen.js contains
jQuery(document).ready(function() {
/* Contact Form */
if(jQuery('#contactform').length != 0){
addForm('#contactform');
}
/* Newsletter Subscription */
if(jQuery('#newsletterform').length != 0){
addForm('#newsletterform');
}
});
/* Contact Form */
function addForm(formtype) {
var formid = jQuery(formtype);
var emailsend = false;
formid.find("button[name=send]").click(sendemail);
function validator() {
var emailcheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var othercheck = /.{4}/;
var noerror = true;
formid.find(".requiredfield").each(function () {
var fieldname = jQuery(this).attr('name');
var value = jQuery(this).val();
if(fieldname == "email"){
if (!emailcheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}else{
if (!othercheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}
})
if(!noerror){
formid.find(".errormessage").fadeIn();
}
return noerror;
}
function resetform() {
formid.find("input").each(function () {
jQuery(this).val("");
})
formid.find("textarea").val("");
emailsend = false;
}
function sendemail() {
formid.find(".successmessage").hide();
var phpfile = "";
if(formtype=="#contactform"){
phpfile = "../php/contact.php";
}else if(formtype=="#newsletterform"){
phpfile = "php/signup.php";
}else{
phpfile = "";
}
if (validator()) {
if(!emailsend){
emailsend = true;
formid.find(".errormessage").hide();
formid.find(".sendingmessage").show();
jQuery.post(phpfile, formid.serialize(), function() {
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
resetform();
});
}
}
return false
}
}
and my php file contact.php
<?php
$to = "developer#vakilspremedia.com"; /* Enter your email adress here */
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$companyname = trim($_POST['companyname']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$message = str_replace(chr(10), "<br>", $_POST['message']);
$body = "<html><head><title>Contact Form Email</title></head><body><br>";
$body .= "Name: <b>" . $name . "</b><br>";
$body .= "Designation: <b>" . $designation . "</b><br>";
$body .= "Company Name: <b>" . $companyname . "</b><br>";
$body .= "Email: <b>" . $email . "</b><br>";
$body .= "Phone: <b>" . $phone . "</b><br><br>";
$body .= "Message:<br><hr><br><b>" . $message . "</b><br>";
$body .= "<br></body></html>";
$subject = 'Contact Form Email from ' . $name;
$header = "From: $to\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=utf-8\n";
mail($to, $subject, $body, $header);
?>
The validation works perfect but when I enter values in all field it shows sending... as the message and doesn't show Email successfully sent at all even after hours and hours of waiting. It seems it does nothing after I click on send button.
Modify ur js for this code make sure phpfile var have url path or put contact.php in same directory
jQuery.post('contact.php', formid.serialize(), function() {
console.log('success');
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
resetform();
});

Categories

Resources