PHPmailer - preg_match() expects parameter 2 to be string, array given - php

The code below used to work fine a while ago, sending emails with images to Blogger's email; or sending emails to any provided email address. Unfortunately I have no idea when it stopped working and how to fix it. The error given is
Array ( [type] => 2 [message] => preg_match() expects parameter 2 to be string, array given [file] => /var/www/html/PHPMailer.php [line] => 4533 )
Below is the page, I appreciate if someone could fix it.
<?php
// error_reporting(0);
// ini_set('display_errors', 0);
var_dump($_POST["name"]);
var_dump($_POST["age"]);
var_dump($_FILES);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$error = '';
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
//age
if(empty($_POST["age"]))
{
$error .= '<p><label class="text-danger">Please Enter your Age</label></p>';
}
else
{
$age = clean_text($_POST["age"]);
if(!preg_match("/^[0-9]*$/",$age))
{
$error .= '<p><label class="text-danger">Only numbers allowed</label></p>';
}
}
//age
//i am
if(empty($_POST['formGender']))
{
$error .= '<p><label class="text-danger">Select your gender</label></p>';
}
//i am
//looking for
if(empty($_POST['formGender2']))
{
$error .= '<p><label class="text-danger">Select your Partner</label></p>';
}
//looking for
//for
if(empty($_POST['formGender3']))
{
$error .= '<p><label class="text-danger">Select your preferences</label></p>';
}
//for
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">City/Town is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
//country
if(empty($_POST["country"]))
{
$error .= '<p><label class="text-danger">Country is required</label></p>';
}
else
{
$subject = clean_text($_POST["country"]);
}
//country
if(empty($_POST["youtube"]))
{
// $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$youtube = clean_text($_POST["youtube"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if(empty($_POST["phone"]))
{
// $error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$phone = clean_text($_POST["phone"]);
}
if($error == '')
{
if (array_key_exists('userfile', $_FILES)) {
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$ip = $_SERVER['REMOTE_ADDR'];
require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';
$mail = new PHPMailer;
$mail->IsSMTP(); //Sets Mailer to send message using SMTP
$mail->Host = 'smtp.gmail.com'; //Sets the SMTP hosts
$mail->Port = '465'; //Sets the default SMTP server port
$mail->SMTPAuth = true; //Sets SMTP authentication. Utilizes the Username and Password variables
$mail->Username = 'asdfdfgndfbgasdf'; //Sets SMTP username
$mail->Password = 'asdfsgdbfsfg'; //Sets SMTP password
$mail->SMTPSecure = 'ssl'; //Sets connection prefix. Options are "", "ssl" or "tls"
$mail->From = $_POST["email"]; //Sets the From email address for the message
$mail->FromName = $_POST["name"]; //Sets the From name of the message
$mail->AddAddress('asdfasdf.dfnghdfghfgh#blogger.com', 'Name');//Adds a "To" address
$mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
$mail->WordWrap = 1000; //Sets word wrapping on the body of the message to a given number of characters
$mail->IsHTML(true); //Sets message type to HTML
$mail->Subject = $_POST["name"] . ', ' . $_POST['formGender'] . ' (' . $_POST["age"] . ') looking to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"]; //Sets the Subject of the message
if(empty($_POST["youtube"]))
{
$mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' . $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><div id="regip">Profile registered from IP <strong>' . $ip . '</strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:315px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>'; //An HTML or plain text message body
}
if($_POST["youtube"])
{
$mail->Body = '<div id="intro"> Meet <span style="text-transform: capitalize;">' . $_POST["name"] . '</span>, a ' . $_POST["age"] . ' yo ' . $_POST["formGender"] . ' looking for ' . $_POST["formGender2"] . ' to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ' ' . $_POST["country"] . '. If you want to ' . $_POST["formGender3"] . ' in ' . $_POST["subject"] . ', ' . $_POST["country"] . ', leave a message for ' . $_POST["name"] . ' on this page or use the contact details below.<br/><br/><strong>Email</strong> ' . $_POST["email"] . ' <br/><strong>Phone</strong> ' . $_POST["phone"] . '.</div><div id="beforeblock">... more about ' . $_POST["name"] . ' below, in their own words: </div><div style="clear:both;"></div><blockquote>' . $_POST["message"] . '</blockquote><iframe loading="lazy" style="width:100%;min-height:315px;height:auto;margin:0 5px;" width="560" height="315" src="https://www.youtube.com/embed/' . $_POST["youtube"] . '" title="Video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" id="youtubeframe" allowfullscreen></iframe><div id="regip">Profile registered from IP <strong>' . $ip . '</strong></div><iframe width="600" height="500" id="gmap_canvas" src="https://maps.google.com/maps?q=' . $_POST['subject'] . ',' . $_POST['country'] . '&t=&z=10&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" loading="lazy" style="width:100%;max-width:100%;height:auto;min-height:200px;"></iframe><br/><span id="tags">' . $_POST['formGender'] . ', ' . $_POST['subject'] . ', ' . $_POST['country'] . '</span>'; //An HTML or plain text message body
}
$mail->set('X-Priority', '3'); //Priority 1 = High, 3 = Normal, 5 = low
//photo
//Attach multiple files one by one
for ($ct = 0, $ctMax = count($_FILES['userfile']['tmp_name']); $ct < $ctMax; $ct++) {
//Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
//Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct])) . '.' . $ext;
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to upload the photos ' . $filename;
}
} else {
$msg .= 'Failed to move photo to ' . $uploadfile;
}
}
// $mail->AddAttachment($image_location);
//photos
if($mail->Send()) //Send an Email. Return true on success or false on error
{
$error = '<label class="text-success">Thank you for registering your profile. It will be visible soon after aproval.</label><style>.form-container {display:none!important;}</style>';
}
else
{
$error = '<label class="text-danger">Your profile was not registered. Please try again!</label>';
// $errorMessage = error_get_last()['message'];
// echo $errorMessage;
// var_dump($_FILES);
print_r(error_get_last());
}
$name = '';
$age = '';
$email = '';
$subject = '';
$country = '';
$message = '';
$msg = '';
$youtube = '';
} //if img check ends
} //if error ends
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
.form-container{width:96%;MAX-WIDTH:96%;margin:0 2%;}
.form-group{margin-bottom:10px}
.btn{background:#1c94ff;padding:4px 8px;border:none;box-shadow:2px 1px 1px #d3d3d3;color:#fff;outline:0;font-size:17px;cursor:pointer;width:100%}
label{display:block;margin-bottom:2px}
.form-group .form-control{width:100%;outline:0;padding:5px;border:none;background:#d1d1d1;border-bottom:2px solid #1c94ff;font-size:16px}
.has-success .form-control{border-bottom:2px solid #168b3f}
.has-danger .form-control{border-bottom:2px solid #dc1d34}
.form-group .text-help{color:#dc1d34}
.inline-label label{display:inline}
.pristine-error{display:table}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined'){
document.write(unescape("%3Cscript src='//cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.slim.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
</head>
<body>
<?php echo $error; ?>
<div style="float:right;font-style: italic;"><span style="color:red;font-style: normal;">!</span> = mandatory</div>
<div class="form-container">
<form method="post" enctype="multipart/form-data" id="registercafebar">
<div class="form-group">
<label><span style="color:red">!</span> Name</label>
<input type="text" name="name" required minlength="3" maxlength="20" placeholder="Enter Your Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> Age</label>
<input required type="number" minlength="2" maxlength="2" min="16" max="99" name="age" placeholder="Enter your real age" class="form-control" value="<?php echo $age; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> I am a</label>
<select required name="formGender" class="form-control">
<option value="">Select your gender at birth</option>
<option value="woman">Woman</option>
<option value="man">Man</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> Looking for a</label>
<select name="formGender2" required class="form-control">
<option value="">Select who you are looking for</option>
<option value="man">Man</option>
<option value="woman">Woman</option>
<option value="couples">Couple</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> For</label>
<select name="formGender3" required class="form-control">
<option value="">Select what your intentions are</option>
<option value="date">Dating</option>
<option value="chat">Chat</option>
<option value="marry">Marriage</option>
<option value="have sex">Sex</option>
</select>
</div>
<div class="form-group">
<label><span style="color:red">!</span> City</label>
<input type="text" name="subject" required class="form-control" minlength="2" maxlength="25" placeholder="Enter your City/Town" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> Country</label>
<input type="text" name="country" required class="form-control" minlength="2" maxlength="20" placeholder="Enter your Country" value="<?php echo $country; ?>" />
</div>
<div class="form-group">
<label><span style="color:red">!</span> About me </label>
<textarea name="message" cols="30" rows="5" minlength="200" maxlength="1000" required class="form-control" placeholder="Describe who you are and what you are looking for, write about the things you like or dislike or talk about your hobbies, but keep it spam free."><?php echo $message; ?></textarea>
</div>
<div class="form-group">
<label><span style="color:red">!</span> Email</label>
<input type="email" name="email" class="form-control" minlength="6" maxlength="30" required placeholder="Enter Your Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Phone</label>
<input type="number" name="phone" class="form-control" minlength="4" maxlength="25" placeholder="Enter Your Phone" value="<?php echo $phone; ?>" />
</div>
<div class="form-group">
<label>Youtube video ID <br/><span style="text-decoration: line-through;">https://www.youtube.com/watch?v=</span><strong style="padding:0 5px;border:1px solid gray;">fhgnfyhfth</strong></label>
<input type="text" name="video" class="form-control" minlength="5" maxlength="15" placeholder="Enter Your Youtube video" value="<?php echo $youtube; ?>" />
</div>
<div class="form-group">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
<span style="color:red">!</span> Photos:
<input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
</div>
<div id="message"><span style="color:red">!</span> Please verify:</div>
<div id="success">Perfect ✓</div>
<div id="fail"><span style="color:red">!</span> Try again</div>
<p id="question"></p> <input id="ans" type="text">
<p><span style="color:red">!</span> Are you human?<br/> No <input type="checkbox" name="no"> Yes <input type="checkbox" name="yes" required></p>
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
<div class="form-group inline-label">
<span style="color:red">!</span> <input id="ch1" type="checkbox" name="future" required data-pristine-required-message="You must accept the terms and conditions"/>
<label for="ch1">I accept the terms and conditions</label><br/>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Register" class="btn btn-info" disabled="disabled" /><!--disabled="disabled"-->
</div>
</form>
</div>
<div class="timer" onload="timer(1800)">
<div class="time">
<strong>Time until the page will refresh: <span id="time">Loading...</span></strong>
</div>
</div>
<br/>
<script>
var total;
function getRandom() {
return Math.ceil(Math.random() * 20);
}
function createSum() {
var randomNum1 = getRandom(),
randomNum2 = getRandom();
total = randomNum1 + randomNum2;
jQuery("#question").text(randomNum1 + " + " + randomNum2 + "=");
jQuery("#ans").val('');
checkInput();
}
function checkInput() {
var input = jQuery("#ans").val(),
slideSpeed = 200,
hasInput = !!input,
valid = hasInput && input == total;
jQuery('#message').toggle(!hasInput);
jQuery('input[type=submit]').prop('disabled', !valid);
jQuery('#success').toggle(valid);
jQuery('#fail').toggle(hasInput && !valid);
}
jQuery(document).ready(function() {
//create initial sum
createSum();
// On "reset button" click, generate new random sum
jQuery('input[type=reset]').click(createSum);
// On user input, check value
jQuery("#ans").keyup(checkInput);
//cookie registered
});
</script>
</body>
</html>
If it matters, I am using PHP 7.3, NginX. From my knowledge, same config as when the script used to work.
Also tried this:
Adding the following right after <?php, following the comments
var_dump($_POST["name"]);
var_dump($_POST["age"]);
var_dump($_FILES);
Returns this before submitting the form:
NULL NULL array(0) { }
And this after submitting the form:
string(14) "Johny macaroni" string(2) "22" array(1) { ["userfile"]=> array(5) { ["name"]=> array(1) { [0]=> string(8) "oslo.png" } ["type"]=> array(1) { [0]=> string(9) "image/png" } ["tmp_name"]=> array(1) { [0]=> string(14) "/tmp/phpen1nVm" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(28358) } } }

In the end, the problem was not related to my script at all. It was the Gmail and Outlook SMTP services that, for some reason, refused to honor the script's SMTP requests; both of them.
So, after switching to a 3rd free SMTP provider, everything started to work as it did before. Solved.

There are quite a few nonsensical things in here. It looks like you've adapted this from a very old example.
The require statements inside the function mean that this will crash the second time you call the function.
You're preprocessing the email address into $email but not using that variable when actually setting the recipient.
You're forging the from address, which is likely to mean your messages will not be delivered.
Sending a copy to the supposed sender means your script is a spam gateway that can be abused to send arbitrary content to arbitrary recipients. This is bad and will be mercilessly exploited by spammers.
Port is an integer, not a string:
$mail->Port = 465;
This will do nothing useful:
$mail->set('X-Priority', '3');
If you want to add a custom header, use addCustomHeader. If you want to set a priority, set the Priority property, which is also an int:
$mail->Priority = 3;
Overall, base your code on the examples provided, particularly the contact form example.
Update
Now that we have a location for the error, we can see that it's in the call to PHPMailer::mb_pathinfo, which passes in $_FILES['userfile']['name'] as the $path parameter, and not in addCC as I had guessed. The HTML form declares this input as an array of file type allowing multiple values:
<input name="userfile[]" required type="file" multiple="multiple" accept="image/*">
This means that $_FILES['userfile']['name'] will be an array, not a string (see the PHP docs), which is the cause of the error.
The fix here is to get the name property of the individual file, not the array of all of them, which is done by adding the array index, so this line:
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
should be:
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'][$ct], PATHINFO_EXTENSION);
This bug was previously present in the example code that this was originally adapted from, though that was fixed 6 months ago.

Related

WordPress custom Contact Form in Bootstrap modal is not showing validation & submission response

For my WordPress (v5.5.1) I am using Bootstrap and built a Custom Contact Form in Bootstrap Modal with below HTML (followed this tutorial: https://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/).
<form id="contact-form" action="<?php echo get_site_url(); ?>" method="post">
<div class="modal-body">
<?php echo $response; ?>
<div class="form-group">
<input class="form-control my-2" type="text" name="message_name" size="50" placeholder="Your full name" value="<?php echo esc_attr($_POST['message_name']); ?>">
<input class="form-control my-2" type="email" name="message_email" size="50" placeholder="Email address" value="<?php echo esc_attr($_POST['message_email']); ?>">
<input class="form-control my-2" type="tel" name="message_tel" size="50" placeholder="Country code, Phone number" value="<?php echo esc_attr($_POST['message_tel']); ?>">
<textarea class="form-control my-2" name="message_text" rows="2" placeholder="Your message" value="<?php echo esc_attr($_POST['message_text']); ?>"></textarea>
<input class="form-control my-2" type="text" name="message_human" placeholder="Human check: Enter 2">
<input type="hidden" name="message_url" value="<?php the_permalink(); ?>">
<input type="hidden" name="message_page" value="<?php the_title(); ?>">
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="submitted" value="1">
<button type="submit" value="Submit" class="btn btn-search form-control">Send Enquiry</button>
</div>
Below the function to validate the Forms & show responses while Form submission:
function validateform() {
//response generation function
$response = "";
//function to generate response
function contact_g_form_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
}
//response messages
$not_human = "Enter current year in numbers.";
$missing_content = "Missing something.";
$email_invalid = "Check your Email address.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! We got your enquiry.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$fromEmail = $name . '<' . $email . '>';
$tel = $_POST['message_tel'];
$text = $_POST['message_text'];
$url = $_POST['message_url'];
$page = $_POST['message_page'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = '[General Enquiry] ' . $name . ' | Phone Number:' . $tel;
$headers = 'From: ' . $fromEmail . "\r\n" .
'Reply-To: ' . $email . "\r\n";
$message = '<html><body><h1>New general enquiry from ' . $name . '!</h1>'
. '<p>Email: ' . $email . '</p>'
. '<p>Phone Number: ' . $tel . '</P>'
. '<p>Inquiry: ' . $text . '</P>'
. '<p>From page: <b>' . $page . '</b></P>'
. '<p>Page URL: ' . $url . '</p>'
. '</body></html>';
if (!$human == 0) {
if ($human != 2) {
contact_g_form_response("error", $not_human); //not human!
} else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
contact_g_form_response("error", $email_invalid);
} else { //email is valid
//validate presence of name, phone number
if (empty($name) || empty($tel)) {
contact_g_form_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to, $subject, $message, implode("\r\n", $headers)); //mail to admin - striptags removing formatting
// $sent2 = wp_mail($email, $subject, $body, $headers); //mail to visitor
// if ($sent || $sent2) {
if ($sent) {
contact_g_form_response("success", $message_sent); //message sent!
} else {
contact_g_form_response("error", $message_unsent); //message wasn't sent
}
}
}
}
} else if ($_POST['submitted']) {
contact_g_form_response("error", $missing_content);
}
}
In the earlier versions of WordPress the email was being sent without validation, with v5.5.1 upgrade, the Modal is closing without any validation and the email is also not being sent.
You Just Need To replace this:
<form id="contact-form" action="<?php echo get_site_url();?>" method="post">
With This:
<form id="contact-form" method="post">
Because You are displaying the error on the same page but on click of the submit button the action is taking you to a specific url and that's the reason the validations are not shown.
And This:
if ($type == "success") {
$response = "<div class='message-success text-center'>{$message}</div>";
} else {
$response = "<div class='message-error text-center'>{$message}</div>";
}
With This also:
if ($type == "success") {
$response = $message;
echo $response;
} else {
$response = $message;
echo $response;
}

Honeypot technique for php form

I'm trying use honeypot technique for my custom form on wordpress site.
My form look like that.
<form id="form-1"
action="<?php echo get_template_directory_uri(); ?>/mail.php" method="post" class="order__form form">
<p class="form__title">Order and Receive 30% off</p>
<p class="form__text">fill out this form so you can get sale</p>
<input type="text" name="name" class="form__item" placeholder="Your name">
<input type="email" name="email" required class="form__item" placeholder="Email address">
<p class="robotic" id="pot">
<label>If you're human leave this blank:</label>
<input name="robotest" type="text" id="robotest" class="robotest" />
</p>
<input type="submit" value="Send" class="button form__button">
</form>
Input with name robotest for validation on server side.
This is mail.php code:
<?php
$mess = '';
$mess .= '<hr>';
if($_POST['robotest'] != ''){
$error = "You are a gutless robot.";
} else {
if(isset($_POST['name'])) {
$name = substr(htmlspecialchars(trim($_POST['name'])), 0, 100);
$mess .= '<b>Имя отправителя: </b>' . $name . '<br>';
}
if(isset($_POST['email'])) {
if($_POST['email']!=''){
$email = substr(htmlspecialchars(trim($_POST['email'])), 0, 100);
$mess .= '<b>E-mail: </b>' . $email . '<br>';
}
}
}
$mess .= '<b>Заявка пришла со страницы:</b> ' . $_SERVER["HTTP_REFERER"] .'<br>';
$mess .= '<hr>';
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->AddAddress('xxx2xxx.com','');
$mail->IsHTML(true);
$mail->CharSet = "UTF-8";
$mail->Subject = "new";
$mail->From = "new";
$mail->FromName = "new";
$mail->Body = $mess;
if ($mail->Send()) {
header('Location: ../');
} else {
die ('Mailer Error: ' . $mail->ErrorInfo);
}
header("Location: /thanks/");
?>
When I add validation for robotest, this script doesn't work.
You are setting the $error variable but you are not using it anywhere.
If you change the:
$error = "You are a gutless robot.";
To a:
die( "You are a gutless robot." );
You will have what you describe you want to have.

PHP form validation not working after first submit

I'm using a contact form on my website and I'm trying to validate the user input using PHP. The problem with it is that although it will validate the input alright, if you then enter correct details and hit send, it doesn't do anything. I think this is because it's not doing the second part of the if statement after an error has been entered, but I'm not sure how to fix it. Below is the code I'm using so far.
<?php
error_reporting(E_ALL ^ E_NOTICE);
function fix_string($var)
{
if(get_magic_quotes_gpc()) $var = stripslashes($var);
$var = strip_tags($var);
return $var;
}
{
$details = array('name' => fix_string($_POST['name']),
'email' => fix_string($_POST['email']),
'number' => fix_string($_POST['number']),
'message' => fix_string($_POST['message']));
}
$send = $_POST['send'];
$message = "";
$email = $details['email'];
foreach ($details as $field => $detail)
$message .= ucfirst($field) . ": " . $detail . "\r\n";
$to = "smokey.12345#hotmail.co.uk";
$subject = "Website contact form";
$message = wordwrap($message, 70, "\r\n");
$headers = 'From: ' .$email . "\r\n" .
'Reply-To: ' .$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
function trim_value(&$value)
{
$value = trim($value);
}
array_walk($details, 'trim_value');
if ($send)
{
foreach ($details as $field => $detail)
{
if (empty($detail) && $field!='number')
echo "<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>";
}
if (!is_numeric($details['number']))
echo "<p class='error'>Please enter a valid telephone number</p>";
}
else
{
mail($to, $subject, $message, $headers);
echo "<p class='success'>Thank you for your message, you will receive a response shortly.</p>";
}
?>
<div id="contactform">
<form action="" method="post">
<fieldset>
<label for="name">Name:<span class="star">*</span></label> <br />
<input type="text" name="name" id="name" placeholder="Enter your name" maxlength="50" required />
<label for="email">Email:<span class="star">*</span></label> <br />
<input type="email" name="email" id="email" placeholder="Enter your email address" maxlength="100" required />
<label for="number">Telephone: </label><input type="tel" name="number" id="number" placeholder="Enter your phone number" maxlength="12" />
<label for="message">Message:<span class="star">*</span></label>
<textarea name="message" id="message" placeholder="Enter your message" cols="54" rows="5" required></textarea>
<p class="small"><span class="star">*</span> Denotes a required field </p>
<input type="submit" id="send" name="send" value="Send" />
</fieldset>
</form>
I tried changing it to a while loop and just doing the validation until it is valid and then sending the email, however my attempts at this didn't work either.
Could you try change your if ($send) {} block to the following and test?
if ($send) {
$bHasError = false;
foreach ($details as $field => $detail) {
if (empty($detail) && $field!='number') {
echo "<p class='error'>Please fill in the required field: " . ucfirst($field) . "<br /></p>";
$bHasError = true;
}
}
if (!is_numeric($details['number'])) {
echo "<p class='error'>Please enter a valid telephone number</p>";
$bHasError = true;
}
if (!$bHasError) {
mail($to, $subject, $message, $headers);
echo "<p class='success'>Thank you for your message, you will receive a response shortly.</p>";
}
}

Pass a variable from one PHP file to another via $.post

I have a contact form that passes the data via jQuery $.post.
JS
$(function () {
$("#contact_form").submit(function (a) {
a.preventDefault();
$.post("<?php echo home_url('/_asset/contact.php'); ?>", {
contact_name : $("#contact_name").val(),
contact_email : $("#contact_email").val(),
contact_subject : $("input:radio[name=subject]:checked").val(),
contact_textarea: $("#contact_textarea").val(),
contact_postid : $("#contact_postid").val(),
}, function (a) {
$("div#response").removeClass("hidden");
$("div#response").delay(1E3).html(a);
});
});
});
contact.php
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST["contact_textarea"];
$contact_postid = $_POST['contact_postid'];
$contact_address = $_SERVER['REMOTE_ADDR'];
if( empty($contact_name) && empty($contact_email) && empty($contact_subject) && empty($contact_message) ) {
die('You must fill out all fields amigo!');
}
// Build that email boy!
if( !empty($contact_postid) ) { $email_id = ' (' . $contact_postid . ')'; }
$email_to = 'email#example.com';
$email_subject = 'Contact Form: ' . $contact_subject . $email_id;
$email_header = 'From: ' . $contact_name . '<' . $contact_email . '>' . "\r\n";
$email_header .= 'Reply-To:' . $contact_email . "\r\n";
$email_header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$email_message = nl2br($contact_message);
// Try sending the email
if(!mail($email_to, $email_subject, $email_message, $email_header)){
$status = 'red';
die('Error sending email.');
} else {
$status = 'green';
die('Email sent!');
}
PHP form
<div class="respond_form">
<form method="post" id="contact_form">
<h2>Let's get contacting!</h2>
<div id="response" class="hidden alert <?php echo $status; ?>"></div>
<div class="line">
<label for="contact_name" title="Please enter your name (required)">Your name <span class="required">*</span></label>
<input type="text" name="contact_name" id="contact_name" tabindex="1" placeholder="John Smith" required="required"/>
</div>
<div class="line">
<label for="contact_email" title="Please enter your email (required)">Your email (so we can contact you) <span class="required">*</span></label>
<input type="email" name="contact_email" id="contact_email" tabindex="2" placeholder="mail#example.com" required="required"/>
</div>
<?php if( isset($_GET['subject']) ) { ?>
<input hidden="hidden" name="subject" type="radio" value="<?php echo $_GET['subject']; ?>" checked="checked">
<?php if( isset($_GET['PostID']) ) { echo '<input hidden="hidden" id="contact_postid" name="postid" type="input" value="' . $_GET['PostID'] . '">'; } ?>
<?php } else { ?>
<div class="line">
<label>What is the message in regards to? <span class="required">*</span></label>
<ul style="list-style:none; margin: 0; padding: 0;">
<label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Advertising"<?php if( $_GET['subject'] == 'advertising' ) { echo ' checked="checked"'; } ?>>Advertising</label>
<label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Contribute an Article"<?php if( $_GET['subject'] == 'contribute' ) { echo ' checked="checked"'; } ?>>Contribute an Article</label>
</ul>
</div>
<?php } ?>
<div class="line">
<label for="contact_textarea" title="Briefly explain your message (required)">Briefly explain your message <span class="required">*</span></label>
<textarea name="contact_textarea" id="contact_textarea" rows="10" tabindex="3" maxlength="500" required="required"></textarea>
</div>
<input type="submit" id="contact_send" name="contact_send" class="button glow" value="Send Message"/>
</form>
</div>
As you can see, I've tried setting a $status in the mail() function but that didn't work. I'm not entirely sure what's going on with the whole thing (found it ages ago and just built around it) but I know the die() message emits into the div#response.
Effectively I was hoping to add a class to the div#response if the email was successful or not.
OH! and incase someone wants to comment on the lack of security, or checking of $_POST data, I've stripped it for here :]
$.post sends the data to contact.php and loads its response.
In your case, the response is text that can be "Error sending email." or "Email sent!" (from what you posted) so you just need to test the value and add the related class.
$(function () {
$("#contact_form").submit(function (a) {
a.preventDefault();
$.post("<?php echo home_url('/_asset/contact.php'); ?>", {
contact_name : $("#contact_name").val(),
contact_email : $("#contact_email").val(),
contact_subject : $("input:radio[name=subject]:checked").val(),
contact_textarea: $("#contact_textarea").val(),
contact_postid : $("#contact_postid").val(),
}, function (a) {
$("div#response").removeClass("hidden").addClass( (a=="Email sent!") ? "email-success" : "email-error" );
$("div#response").delay(1E3).html(a);
});
});
});

Wordpress Contact Form Subject Woes

One of the problems I was experiencing with my last site was the Contact Form - it uses a static subject approach.. which is fine - but the problem is if you use Gmail, then it will group emails of the same subject which isn't ideal, especially if you expect a lot of traffic that way.
On the theme I'm using there's a Subject field, but it doesn't seem to be utilized at all. When I sent my test message, I received:
EMAIL SUBJECT: .am - message from contact form
Site: .am
Name: Alex
Email: test#test.tld
Subject: .am - message from contact form
Message: Test body.
So whatever text I entered into the subject field was completely ignored, and then static text was pulled from the e-mail subject and repeated, again, in the body.
I've located the code in the respective page (I think?).
APOLLO13.PHP
if (empty($name))
$name_error = true;
if (empty($email) || !is_email($email))
$email_error = true;
if (empty($subject))
$subject_error = true;
if (empty($content))
$content_error = true;
if ($name_error == false && $email_error == false && $content_error == false && $subject_error == false) {
$subject = $site . __(' - message from contact form', TPL_SLUG);
$body = __('Site: ', TPL_SLUG) . $site . "\n\n"
. __('Name: ', TPL_SLUG) . $name . "\n\n"
. __('Email: ', TPL_SLUG) . $email . "\n\n"
. __('Subject: ', TPL_SLUG) . $subject . "\n\n"
. __('Message: ', TPL_SLUG) . $content;
$headers = "From: $name <$email>\r\n";
$headers .= "Reply-To: $email\r\n";
if (wp_mail($email_to, $subject, $body, $headers)) {
$title_msg = __('Success sending form', TPL_SLUG);
} else
$title_msg = __('Something wrong. Try again!', TPL_SLUG);
} else {
$title_msg = __('Error in form', TPL_SLUG);
if (!empty($name))
$name_tag = 'value="' . $name . '"';
if (!empty($email))
$email_tag = 'value="' . $email . '"';
if (!empty($subject))
$phone_tag = 'value="' . $subject . '" title="' . __('General question ...', TPL_SLUG) . '"';
if (!empty($content))
$content_tag = $content;
}
And what I want is, essentially
EMAIL SUBJECT: $site | $subject-user-entered
Name:
Email:
Message:
How would I go about amending the code to do that? Because this:
$subject = $site . __(' - message from contact form', TPL_SLUG);
. __('Subject: ', TPL_SLUG) . $subject . "\n\n"
Seems a little pointless.
EDIT
I've found the code for the form itself if that's of any help:
<form action="http<?php echo $ssss ?>://<?php echo $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] ?>"
method="post" id="contact-form-<?php echo $form_iter ?>" class="contact-form styled-form">
<div class="submit_inputs">
<div<?php echo ($name_error ? ' class="error"' : '') ?>>
<input id="apollo13-contact-name" name="apollo13-contact-name" type="text" value=""/>
<label for="apollo13-contact-name">
<?php echo __('Name', TPL_SLUG) ?>
<span> (<?php echo __('required', TPL_SLUG) ?>)</span>
</label>
</div>
<div style="clear: both;"></div>
<div<?php echo ($name_error ? ' class="error"' : '') ?>>
<input id="apollo13-contact-email" name="apollo13-contact-email" type="text" value="" class="email"/>
<label for="apollo13-contact-email">
<?php echo __('Email', TPL_SLUG) ?>
<span> (<?php echo __('required', TPL_SLUG) ?>)</span>
</label>
</div>
<div style="clear: both;"></div>
<div<?php echo ($name_error ? ' class="error"' : '') ?>>
<input class="placeholder" id="apollo13-contact-subject" name="apollo13-contact-subject" type="text"
value=""/>
<label for="apollo13-contact-subject">
<?php echo __('Subject', TPL_SLUG) ?>
</label>
</div>
</div>
<div style="clear: both;"></div>
<div<?php echo ($name_error ? ' class="error"' : '') ?>>
<textarea id="apollo13-contact-content" name="apollo13-contact-content" rows="10" cols="40"></textarea>
</div>
<div>
<input type="hidden" name="apollo13-contact-form" value="send"/>
<input id="contact-submit" type="submit" value="<?php echo __('Submit form', TPL_SLUG) ?>"/>
</div>
</form>
I really can't say for certain as I don't know where $subject gets its original value nor do I know what your html form looks like.
$subject = $site . __(' - message from contact form', TPL_SLUG);
Would possibly change to
$subject = $site . ' | ' . $subject;
And the $body would look like the following:
$body = __('Site: ', TPL_SLUG) . $site . "\n\n"
. __('Name: ', TPL_SLUG) . $name . "\n\n"
. __('Email: ', TPL_SLUG) . $email . "\n\n"
. __('Message: ', TPL_SLUG) . $content;

Categories