Incorrect encoding with Cyrillic in PHP contact form - php

I'm new to using PHP and forms so if someone is willing to help, I'll be extremely grateful.
I have a contact form, but it doesn't send any Cyrillic characters correctly. I know that I have to put Content-type: text/plain; charset=UTF-8 somewhere in the code but I have no idea where to put it exactly. The form element is set to post in UTF-8, but it doesn't seem to work correctly with the PHP file.
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "myemailaddress#mail.com";
$from_email = "";
$continue = "index.php";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if (count($_COOKIE)) {
foreach(array_keys($_COOKIE) as $value) {
unset($_REQUEST[$value]);
}
}
// Validate email field.
if (isset($_REQUEST['email']) && !empty($_REQUEST['email']) && !empty($_REQUEST['family']) && !empty($_REQUEST['about'])) {
$_REQUEST['email'] = trim($_REQUEST['email']);
if (substr_count($_REQUEST['email'], "#") != 1 || stristr($_REQUEST['email'], " ")) {
$errors[] = "Email address is invalid";
} else {
$exploded_email = explode("#", $_REQUEST['email']);
if (empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])) {
$errors[] = "Email address is invalid";
} else {
if (substr_count($exploded_email[1], ".") == 0) {
$errors[] = "Email address is invalid";
} else {
$exploded_domain = explode(".", $exploded_email[1]);
if (in_array("", $exploded_domain)) {
$errors[] = "Email address is invalid";
} else {
foreach($exploded_domain as $value) {
if (strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i', $value)) {
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
// Check referrer is from same site.
if (!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']))) {
$errors[] = "You must enable referrer logging to use the form";
}
// Check for a blank form.
function recursive_array_check_blank($element_value) {
global $set;
if (!is_array($element_value)) {
if (!empty($element_value)) {
$set = 1;
}
} else {
foreach($element_value as $value) {
if ($set) {
break;
}
recursive_array_check_blank($value);
}
}
}
recursive_array_check_blank($_REQUEST);
if (!$set) {
$errors[] = "You cannot send a blank form";
}
unset($set);
// Display any errors and exit if errors exist.
if (count($errors)) {
foreach($errors as $value) {
print "$value<br>";
}
exit;
}
if (!defined("PHP_EOL")) {
define("PHP_EOL", strtoupper(substr(PHP_OS, 0, 3) == "WIN") ? "\r\n" : "\n");
}
// Build message.
function build_message($request_input) {
if (!isset($message_output)) {
$message_output = "";
}
if (!is_array($request_input)) {
$message_output = $request_input;
} else {
foreach($request_input as $key = > $value) {
if (!empty($value)) {
if (!is_numeric($key)) {
$message_output. = str_replace("_", " ", ucfirst($key)).
": ".build_message($value).PHP_EOL.PHP_EOL;
} else {
$message_output. = build_message($value).
", ";
}
}
}
}
return rtrim($message_output, ", ");
}
$message = build_message($_REQUEST);
$message = $message.PHP_EOL.PHP_EOL.
"-- ".PHP_EOL.
"Thank you for using the contact form.";
$message = stripslashes($message);
$subject = $_REQUEST['about'];
$subject = stripslashes($subject);
if ($from_email) {
$headers = "From: ".$from_email;
$headers. = PHP_EOL;
$headers. = "Reply-To: ".$_REQUEST['email'];
} else {
$from_name = "";
if (isset($_REQUEST['name']) && !empty($_REQUEST['name'])) {
$from_name = stripslashes($_REQUEST['name']);
}
$headers = "From: {$from_name} <{$_REQUEST['email']}>";
}
mail($my_email, $subject, $message, $headers); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Your mail has been sent!</title>
<meta http-equiv="Content-Type" content="text/html; charset = utf - 8 ">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<center>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<br>Your mail has been sent!
<p>Click here to continue</p>
</center>
</div>
</body>
</html>

Добави това:
$headers = "From: " . $from_email;
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
//новия код (new code)
$headers .= "MIME-Version: 1.0"."\r\n" ."Content-type: text/plain; charset='utf-8'". "\r\n";
Няма да е лошо да сложиш и някаква форма на верификация (картинка с код примерно, който трябва да се въведе, т.нар. CAPTCHA code) преди пращане от юзера, иначе всеки спам бот ще ти ползва формата за пращане на мейли, порови тук има доста начини за справяне с проблема.
Translated: (It is not bad idea to put some sort of verification code, an image with code inside of it, a so called CAPTCHA before sending the email, because otherwise every spam bot from Internet will use your form for mailing, check here for more ways to deal with the problem.)

Related

contact form not giving data

I have issue with fat-free contact form.
My contact form does nothing. Like no success or any kind of error data.
My contact form POST and GET route:
$f3->route('GET #contact: /contact', 'Rimtay\Client->GET_Contact');
$f3->route('POST #contact: /send', 'Rimtay\Client->contactPost');
My contact form POST function:
function contactPost(){
function validateInput($data) {
$bad = array("content-type","bcc:","to:","cc:","href");
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
foreach ($bad as $badString) {
if (preg_match('/('.$badString.')/i',$data)) {
// If it looks like someone is trying to hack
// into the site via the contact page, then just stop.
exit;
}
}
return $data;
}
// define variables and set to empty values
$contactNameError = $contactEmailError = $contactMessageError = "";
$name = $email = $message = $success = "";
if ($f3->exists('POST.name',$name)) {
if ($name !== '') {
$name = validateInput($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$contactNameError = "Wrong name";
} else { // valid name
$f3->set('contactName',$name);
}
} else {
$contactNameError = "name empty";
}
} else {
$contactNameError = "name error";
}
if ($f3->exists('POST.email',$email)) {
if ($email !== '') {
$email = validateInput($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailError = "wrong email";
} else { // valid email
$f3->set('contactEmail',$email);
}
} else {
$contactEmailError = "email empty";
}
} else {
$contactEmailError = "error email";
}
if ($f3->exists('POST.subject',$message)) {
if ($message !== '') {
$f3->set('contactMessage',$message);
} else {
$contactMessageError = "message tühi";
}
} else {
$contactMessageError = "lambi message";
}
if (($contactNameError === '') && ($contactEmailError === '') && ($contactMessageError === '')) {
// send the message
$messageBody = "";
unset($_POST['submit']);
$messageBody = "Name: ".$name."\n";
$messageBody .= "email: ".$email."\n";
$messageBody .= "Subject: Construction - Message from " . $name."\n";
$messageBody .= $message."\n";
$messageBody = wordwrap($messageBody,70);
$to = $f3->get('contactAddresses');
$subject = 'Contact Submitted';
if (mail($to, $subject, $messageBody)){
$f3->set('contactSuccess',true);
} else {
// error sending the email to myself
}
} else {
$f3->set('contactSuccess',false);
}
// Set the content source
$this->f3->set('pageContent','contact.html');
}
my form looks like this:
<form class="form" action="{{ #schemeHost.#PATH }}" method="post">
<textarea class="textarea" name="message" placeholder="Message*">{{ #contactMessage }}</textarea>
<div>
<input type="text" placeholder="Name *" name="name" value="{{ #contactName }}" class="input">
<input type="email" placeholder="Email *" name="email" value="{{ #contactEmail }}" class="input">
</div>
<button class="submit" type="submit" name="submit">Send</button>
</form>
My System isnt giving any success or error messages.
And not sending out contact form messages to email.
I dont see what I'm doing wrong there.
Your code is very prone to errors. For example, the $f3 variable is not defined anywhere in your code.
How does your code handle the errors? It might be that you see no errors because there is no error reporting setup by you and the server is silently not showing the errors. I suggest you to check the error log.
I also suggest to use a form validation library like CakePHP validation library. You will need to learn how to use it, but it will save you big time in the end and your code will be cleaner.

My php mail function is sending blank messages

So as the title states I receive blank emails from my contact form. The php code is below. I've checked the value of $msg and it appears correctly, I've also googled a ton and I can't find anything standard cause that apply to me.
<?php
main();
function main() {
$posted = setVariables();
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);
}
function setVariables() {
$name;
if (isset($_POST['name'])){
$name=$_POST['name'];
if ($name == null) {
$name = "ERROR - name is null";
}
}
$email;
if (isset($_POST['email'])){
$email=$_POST['email'];
if ($email == null) {
$email = "ERROR - email is null";
}
}
$enquiry;
if (isset($_POST['enquiry'])){
$enquiry=$_POST['enquiry'];
if ($enquiry == null) {
$enquiry = "ERROR - enquiry is null";
}
}
$message;
if (isset($_POST['message'])){
$message=$_POST['message'];
if ($message == null) {
$message = "ERROR - message is null";
}
}
$posted = array($name,$email,$enquiry,$message);
return $posted;
}
function setMessage($posted) {
$msg = "Name: " . $posted[0] . "\r\nEmail: " . $posted[1] . "\r\nEnquiry: " . $posted[2] . "\r\nMessage: " . $posted[3];
$msg = wordwrap($msg,70);
$msg = Trim(stripslashes($_POST['Message']));
return $msg;
}
function sendMail($msg) {
$result = mail("social#georgeappleton.co.uk","Contact From Portfolio",$msg, "From: <info#yourdomain.co.uk>");
return $result;
}
function userFeedback($result) {
if ($result == false) {
echo "Message failed to send, please inform me through my email address. social#georgeappleton.co.uk";
} else {
echo "Message Sent!<br/><br/>Returning you to <a href='http://www.georgeappleton.co.uk'>georgeappleton.co.uk</a> in 5 seconds";
}
echo "<script>setTimeout(function() {window.location = 'http://www.georgeappleton.co.uk';},5000);</script>";
}
?>
Thanks guys, appreciate it a lot
-Shardj
Get rid of this line:
$msg = Trim(stripslashes($_POST['Message']));
It's overwriting $msg with the contents of a nonexistent parameter. It already contains the message text, which was in $posted[3].
It's your variable scope. $name withing setVariables()
$name=$_POST['name'];
if (strlen($name) < 1) {$name = "ERROR - name is null";}
$email=$_POST['email'];
if (strlen($email) < 1) {$email = "ERROR - email is null";}
$enquiry=$_POST['enquiry'];
if (strlen($enquiry) < 1) {$enquiry = "ERROR - enquiry is null";}
$posted = array($name,$email,$enquiry,$message);
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);

Wordpress Help Redirect after form submission

I want to have my contact form redirect after form submission. I don't know how do it. This is my code and also it's giving me an error.
<?php
// If the form is submitted
if(isset($_POST['submit'])) {
// Include WordPress Core Functions
$wp_include = '../wp-load.php';
while(!#include_once($wp_include)) { $wp_include = '../'.$wp_include; }
//
// Field Validation
//
// Check to make sure that the name field is not empty
if(trim($_POST['cf_name']) == '') {
$has_error = true;
}
else {
$name = trim($_POST['cf_name']);
}
// Check to make sure that the subject field is not empty
if(trim($_POST['cf_subject']) == '') {
$has_error = true;
}
else {
$subject = trim($_POST['cf_subject']);
}
// Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$has_error = true;
}
elseif(!preg_match("/^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))) {
$has_error = true;
}
else {
$email = trim($_POST['email']);
}
// Check to make sure comments were entered
if(trim($_POST['cf_message']) == '') {
$has_error = true;
}
else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['cf_message']));
}
else {
$message = trim($_POST['cf_message']);
}
}
//
// Send E-Mail
//
// Send the email if there is no error
if(!isset($has_error)) {
// Get recheiver
$receiver = ($_POST['cf_receiver']) ? $_POST['cf_receiver'] : get_option('admin_email');
$receiver = str_replace('[at]', '#', $receiver);
// Headers
$headers = "From: $name <$email>\n";
$headers.= "Content-Type: text/plain; charset=\"UTF-8\"\n";
// Message
if($_POST['cf_email_signature'] && $_POST['cf_email_signature'] != 'none') {
$message.= "\n\n---\n".$_POST['cf_email_signature'];
}
// Send E-Mail
$mail_sent = wp_mail($receiver, $subject, $message, $headers);
if($mail_sent)
echo "<p class='info-box success'>".$_POST['cf_success_msg']."</p>";
else
echo "<p class='info-box error'>The message couldn't be sent because an internal error occured.</p>";
echo "<p class='info-box error'>".$_POST['cf_error_msg']."</p>";
}
}
?>
The function for a redirect in wordpress is wp_redirect, e.g.
if( $mail_sent ) {
wp_redirect( '/my-target' );
exit();
} else {
//output your warning
}

Mail could not be send using php

Hope all of my experts are fine. Buddy's i stuck in a very simple code. Actually i have to insert a form and then fetch values from it to send mail to the user who fills the form. All the values are inserting into the database and also fetch from database but mail is not sending. The same code was sending mail one day ago. But today it is not sending mail. Please help me out in this.
<?php
require("dbconnect.php");
require("DBConnection.php");
session_start();
if(isset($_POST['postadd'])){
$title = $_POST['adtitle'];
$area = $_POST['area'];
$addesc = $_POST['addesc'];
$email = $_POST['email'];
$showemail = $_POST['showemail'];
$userpic = ($_FILES['pic1']['tmp_name']);
$compath = "UploadPictures/".md5($_FILES['pic1']['name']);
$comFileType=$_FILES['pic1']['type'];
$comFileSize=$_FILES['pic1']['size'];
$comFileSize=$comFileSize/1024;
if($comFileSize<1000)
{
$arrFileType=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType,$arrFileType))
{
move_uploaded_file($userpic,$compath);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic2 = ($_FILES['pic2']['tmp_name']);
$compath2 = "UploadPictures/".md5($_FILES['pic2']['name']);
$comFileType2=$_FILES['pic2']['type'];
$comFileSize2=$_FILES['pic2']['size'];
$comFileSize2=$comFileSize2/1024;
if($comFileSize2<1000)
{
$arrFileType2=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType2,$arrFileType2))
{
move_uploaded_file($pic2,$compath2);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic3 = ($_FILES['pic3']['tmp_name']);
$compath3 = "UploadPictures/".md5($_FILES['pic2']['name']);
$comFileType3=$_FILES['pic3']['type'];
$comFileSize3=$_FILES['pic3']['size'];
$comFileSize3=$comFileSize3/1024;
if($comFileSize3<1000)
{
$arrFileType3=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType3,$arrFileType3))
{
move_uploaded_file($pic3,$compath3);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic4 = ($_FILES['pic4']['tmp_name']);
$compath4 = "UploadPictures/".md5($_FILES['pic4']['name']);
$comFileType4=$_FILES['pic4']['type'];
$comFileSize4=$_FILES['pic4']['size'];
$comFileSize4=$comFileSize4/1024;
if($comFileSize4<1000)
{
$arrFileType4=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType4,$arrFileType4))
{
move_uploaded_file($pic4,$compath4);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$agree = $_POST['checkbox'];
$subcat = $_SESSION['subcat'];
$cat = $_SESSION['cat'];
$rand = rand();
$datecreated = date("Y-m-d h:i:s");
$obj = new DBConnection();
$arr_Field = array("title","location","post","email","radio","pic1","pic2","pic3","pic4","agree","cat","subcat","random","datecreated");
$arr_values = array("$title","$area","$addesc","$email","$showemail","$compath","$compath2","$compath3","$compath4","$agree", "$cat", "$subcat" ,"$rand","$datecreated");
$obj->InsertRecord("ads",$arr_Field,$arr_values) or die (mysql_error());
$object = new DBConnection();
$condition = "ORDER BY id DESC LIMIT 1";
$selquery = $object->SelectRecord(array("*"),"ads","$condition") or die(mysql_error());
while($get = mysql_fetch_array($selquery)){
$email = $get['email'];
$id = $get['id'];
}
//echo $email;
//exit();
$to = $email;
$subject = "Admin";
$message = "
<html>
<head>
<title>Admin</title>
</head>
<body>
<p>Please Click on this Link to verify your post</p>
<p><a href='http://almughnisolutions.com/almughniclassified/summary.php?summary=".$id."'>http://almughnisolutions.com/almughniclassified/summary.php?summary=".$id."</a></p>
</body>
</html>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <admin#almughniclassfied.com>' . "\r\n";
mail($to,$subject,$message,$headers) or die("Mail Cannot sent");
//header("Location:verifyadd.php");
}
?>
It would probably be a safe assumption that your code is not to blame. A cursory review of it seems like it shuold work if the SMPT server is behaving correctly. I would recommend testing the server. There are a some web based tools to do this:
https://www.wormly.com/test_smtp_server
You could also just use telnet to test from your machine if it's something that will need to be done internally:
http://technet.microsoft.com/en-us/library/aa995718%28v=exchg.65%29.aspx

How to update my php contact email form script to redirect to a url after submit?

I am using this email script (at the bottom). where and what should I include to redirect to a different url after submit? Also, is this script safe enough?
<?php
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "mymail#mail.com";
$from_email = "";
$continue = "/";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."Thank you for using FormToEmail from http://FormToEmail.com";
$message = stripslashes($message);
$subject = "FormToEmail Comments";
$subject = stripslashes($subject);
if($from_email)
{
$headers = "From: " . $from_email;
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
}
else
{
$from_name = "";
if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){$from_name = stripslashes($_REQUEST['name']);}
$headers = "From: {$from_name} <{$_REQUEST['email']}>";
}
mail($my_email,$subject,$message,$headers);
?>
after mail() add
header("Location: anotherlocation.php");
However to your second question, I'd use $_POST instead of $_REQUEST

Categories