Problems with my PHP Form - php

I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A". Also the page redirects automatically without the form first appearing. How do I rectify this?
Here is my code:
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>

you have the redirection outside the main if statement, just move it inside.
Also you are not accessing the right paramater in the array if you get "Array" back.
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'][$i];
}
you will need to change your function

Related

PHP Anti-Spam field

I have a problem with my email form. Everything works fine, except the Anti-Spam field.
The anti-Spam field shows me a wrong answer in all situations. Both if it is true and false, but when i leave the field blank, then the email is send correctly. So this is problem one.
Problem two is: I want when the Anti-Spam answer is correct then a new question not to be generated. I want to remember the question and the answer, when the answer is correct
So look at my code and please help me? what i am doing wrong?
PHP code:
<?php
require './PHPMailer/PHPMailerAutoload.php';
// varijable
$err_name = $err_email = $err_message = $err_forma = $uspesno = $captcha = "";
$name = $email = $message = $user_result = $arg_1 = $arg_2 ="";
// Konfiguracija PHPMailer-a
$mailer = new PHPMailer;
try {
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? $_POST['name'] : FALSE;
$email = isset($_POST['email']) ? $_POST['email'] : FALSE;
$message = isset($_POST['message']) ? $_POST['message'] : FALSE;
$user_result = isset($_POST['result']) ? $_POST['result'] : FALSE;
$arg_1 = isset($_POST['arg_one']) ? $_POST['arg_one'] : FALSE;
$arg_2 = isset($_POST['arg_two']) ? $_POST['arg_two'] : FALSE;
$mailer->From = $email; // Email posaljioca
$mailer->FromName = "Nova Porudzbina"; // Ime Posaljioca
$mailer->AddAddress("blabla#gmail.com"); //adresa na koju se salje
$mailer->isHTML(TRUE); // set email format to HTML
$mailer->WordWrap = 50; // set word wrap to 50 characters
$mailer->CharSet = "utf-8"; //"ukljucuje" cirlicna slova, kao i latinicna sa kvacicama
$mailer->Subject = 'zahtev za podršku: ' . $naziv_servera;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$name_exp = "/^[A-Za-z\p{L} .'-]{2,40}+$/u"; // Dozvoljava naša slova i ograničava da najmanje može 2 a najviše 40 karaktera
if (!preg_match($name_exp, $name)) {
$err_name .= 'Vaše ime nije validno.';
}
$email = test_input($_POST["email"]);
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email)) {
$err_email .= 'Vaša e-mail adresa nije validna.';
}
$message = test_input($_POST["message"]);
$message_exp = "/^[A-Za-z\p{L} .'-]{2,400}+$/u";
if (!preg_match($message_exp, $message)) {
$err_message .= 'Vaša poruka nije validna.';
}
$user_result = test_input($_POST["result"]);
if($total <> $user_result) {
$captcha .= 'Anti-spam odgovor koji ste uneli nije tačan.';
}
}
// Body
$body = "<h2 style='background: red; color: #fff;'>Nova Porudzbina</h2>";
$body .= "<b>Ime i Prezime:</b>" . $name . "<br>";
$body .= "<b>Email:</b>" . $email . "<br>";
$body .= "<b>Poruka:</b>" . $message . "<br>";
$mailer->Body = $body;
// Posalji
if (strlen($err_name == "" && $err_email == "" && $err_message == "" && $total == $user_result)) {
$mailer->send(); // ako nema nikakve greške - pošalji e-mail
$uspesno .= 'Vasa poruka je poslata';
}
}
}
catch (phpmailerException $ex) {
echo $ex->errorMessage();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function generateFieldNumber($min = 1, $max = 3)
{
return rand(1, 3);
}
function createCaptcha($arg_1 = '', $arg_2 = '', $total = 0)
{
if(isset($_POST['submit'])) {
$arg_1 = $_POST['arg_one'];
$arg_2 = $_POST['arg_two'];
$user_result = $_POST['result'];
$total = $arg_1 + $arg_2;
}
}
HTML code:
<?php
include "send_email.php";
?>
<?php createCaptcha(); ?>
<span><?php echo $uspesno;?></span>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<div class="name">Name:</div>
<input name="name" type="text" value="<?php echo $name;?>" size="30"/>
<span><?php echo $err_name;?></span>
<div class="email">Email:</div>
<input name="email" type="text" value="<?php echo $email;?>" size="30"/>
<span><?php echo $err_email;?></span>
<div class="message">Message:</div>
<textarea name="message" rows="7" cols="30"><?php echo $message;?></textarea><br>
<span><?php echo $err_message;?></span><br><br>
<label>Anti-Spam:</label>
<input type="text" name="arg_one" value="<?php echo generateFieldNumber();?>" size="2">
+ <input type="text" name="arg_two" value="<?php echo generateFieldNumber();?>" size="2">
= <input type="text" name="result" value="<?php echo $user_result;?>" size="2">
<span><?php echo $captcha;?></span><br>
<input type="submit" name="submit" value="Submit" id="submit">
</form>
In order to change the values of $user_result inside createCaptcha you need to declare it as global in your function.
function createCaptcha() {
global $user_result, $arg_1, $arg_2, $total;
if(isset($_POST['submit'])) {
$arg_1 = $_POST['arg_one'];
$arg_2 = $_POST['arg_two'];
$user_result = $_POST['result'];
$total = $arg_1 + $arg_2;
}
}
#Alon
Thanks, I found the solution for problem one:
But second problem still exist.
This is solution for problem one:
<?php
require './PHPMailer/PHPMailerAutoload.php';
// varijable
$err_name = $err_email = $err_message = $err_forma = $uspesno = $captcha = "";
$name = $email = $message = $user_result = $arg_1 = $arg_2 = "";
// Konfiguracija PHPMailer-a
$mailer = new PHPMailer;
try {
if (isset($_POST['submit'])) {
$name = isset($_POST['name']) ? $_POST['name'] : FALSE;
$email = isset($_POST['email']) ? $_POST['email'] : FALSE;
$message = isset($_POST['message']) ? $_POST['message'] : FALSE;
$user_result = isset($_POST['result']) ? $_POST['result'] : FALSE;
$arg_1 = isset($_POST['arg_one']) ? $_POST['arg_one'] : FALSE;
$arg_2 = isset($_POST['arg_two']) ? $_POST['arg_two'] : FALSE;
$total = $arg_1 + $arg_2;
$mailer->From = $email; // Email posaljioca
$mailer->FromName = "Nova Porudzbina"; // Ime Posaljioca
$mailer->AddAddress("blabla#gmail.com"); //adresa na koju se salje
$mailer->isHTML(TRUE); // set email format to HTML
$mailer->WordWrap = 50; // set word wrap to 50 characters
$mailer->CharSet = "utf-8"; //"ukljucuje" cirlicna slova, kao i latinicna sa kvacicama
$mailer->Subject = 'zahtev za podršku: ' . $naziv_servera;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$name_exp = "/^[A-Za-z\p{L} .'-]{2,40}+$/u"; // Dozvoljava naša slova i ograničava da najmanje može 2 a najviše 40 karaktera
if (!preg_match($name_exp, $name)) {
$err_name .= 'Vaše ime nije validno.';
}
$email = test_input($_POST["email"]);
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp, $email)) {
$err_email .= 'Vaša e-mail adresa nije validna.';
}
$message = test_input($_POST["message"]);
$message_exp = "/^[A-Za-z\p{L} .'-]{2,400}+$/u";
if (!preg_match($message_exp, $message)) {
$err_message .= 'Vaša poruka nije validna.';
}
$user_result = test_input($_POST["result"]);
if($total <> $user_result) {
$captcha .= 'Anti-spam odgovor koji ste uneli nije tačan.';
}
}
// Body
$body = "<h2 style='background: red; color: #fff;'>Nova Porudzbina</h2>";
$body .= "<b>Ime i Prezime:</b>" . $name . "<br>";
$body .= "<b>Email:</b>" . $email . "<br>";
$body .= "<b>Poruka:</b>" . $message . "<br>";
$mailer->Body = $body;
// Posalji
if (strlen($err_name == "" && $err_email == "" && $err_message == "" && $captcha == "")) {
$mailer->send(); // ako nema nikakve greške - pošalji e-mail
$uspesno .= 'Vasa poruka je poslata';
}
}
}
catch (phpmailerException $ex) {
echo $ex->errorMessage();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function generateFieldNumber($min = 1, $max = 3)
{
return rand(1, 3);
}
function createCaptcha() {
global $user_result, $arg_1, $arg_2, $total;
if(isset($_POST['submit'])) {
$arg_1 = $_POST['arg_one'];
$arg_2 = $_POST['arg_two'];
$user_result = $_POST['result'];
$total = $arg_1 + $arg_2;
}
}
Problem second maybe...
function generateFieldNumber($min = 1, $max = 3)
{
return rand(1, 3);
if($captcha == "")
/* than remember or stop generate new number ? */
}

PHP mail() vaildation

so i'm still relatively new to PHP and have been building a order form that can validate the fields before sending, as well as checking for spam.
From testing the below code works fine in returning errors and so on, but when I enter correct information I dont get any emails.
It was working fine before i added the Vaildation part to it but now im getting the problem above. Again i am still learning so any pointers would be nice, thanks
<?php
function spamcheck($field) {
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
Form
<?php }
else
{
if (isset($_POST["email"])) {
$mailcheck = spamcheck($_POST["email"]);
if ($mailcheck==FALSE) {
echo "Invalid input";
}
//field vailation
else {
if (isset($_POST['submit'])) {
$errors = array();
if (!empty($_POST["fullname"])) {
$fullname = $_POST["fullname"];
$pattern = "/^[a-zA-Z0-9\_]{2,20}/";
if (preg_match($pattern,$fullname)){ $fullname = $_POST["fullname"];}
else{ $errors[] = 'Your Name can only contain _, 1-9, A-Z or a-z 2-20 long.';}
} else {$errors[] = 'You forgot to enter your First Name.';}
if (!empty($_POST["contact"])) {
$contact = $_POST["contact"];
$pattern = "/^[0-9\_]{6,20}/";
if (preg_match($pattern,$contact)){ $contact = $_POST["contact"];}
else{ $errors[] = 'Your contact number can only be numbers, or is too short';}
} else {$errors[] = 'You forgot to enter your contact number.';}
}
//end vaildation
else{
$fullname = $_POST["fullname"];
$email = $_POST["email"];
$address = $_POST["address"];
$address2 = $_POST["address2"];
$town = $_POST["town"];
$postcode = $_POST["postcode"];
$contact = $_POST["contact"];
$shipping = $_POST["shipping"];
$extra = $_POST["extra"];
$extra = wordwrap($extra, 70);
$message = '
Full Name: ' . $fullname . '
Delivery Address: ' . $address . '
Delivery Address2: ' . $address2 . '
Town/City: ' . $town . '
Postal Code: ' . $postcode . '
Contact: ' . $contact . '
Email Address: ' . $email . '
Special instructions: ' . $extra . '
Shipping Method: ' . $shipping . '
';
mail("myemail#myaddress.com","Order form",$message,"email: $email\n");
echo
"<html>
<body><br><br>
Order successful, we will be in contact shortly<br>
</body>
</html>";
}
}
}
}
?>
<?php
if (isset($_POST['submit'])) {
if (!empty($errors)) {
echo '<hr /><h3>The following occurred:</h3><ul>';
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h3>Your mail could not be sent due to input errors.</h3><hr />';}
else{echo
"<html>
<body><br><br>
Order successful, we will be in contact shortly<br>
</body>
</html>";
}
}
?>
After using error_reporting(E_ALL); ive noticed that im getting an error unexpected 'else' (T_ELSE) for the else at the top of the second block of code, so I tried moving code to :
<?php
error_reporting(E_ALL);
if (!isset($_POST["submit"])) {
}
else
{
And left the form above this so that when the sumbit button is pressed the forms wont dissapear. Which is not giving me any errors but still not email once submitted

Two Form Post Actions - Pass data to another page AND email the data

I am currently working on a form that needs two post actions with one submit button. I am not extremely versed in PHP, only know enough to make my way around current tasks, until now.
Here is the code for the page the form is on:
<?php
if ($_POST) {
if (empty($_POST['first']) ||
empty($_POST['last']) ||
empty($_POST['email']) ||
empty($_POST['location'])) {
$errors = 1;
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors = 2;
} else {
$to = "emailgoeshere#gmail.com";
$subject = "Blah blah blah";
$message .= "Name: ".$_POST['first']." ".$_POST['last']."\n";
$message .= "Email: ".$_POST['email']."\n";
$message .= "Cell Phone: ".$_POST['cell']."\n";
$message .= "Location: ".$_POST['location']."\n";
$from = $_POST['email'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
header('Location: freepass.php');
exit;
}
}
if ($errors == 1) {
$errors = "Please fill out all fields";
} elseif ($errors == 2) {
$errors = "Please enter a valid email";
}
?>
This is the form action:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
This is the code on the page that the data will pass to:
<html>
<head>
</head>
<body>
<?php echo $_POST["first"]; ?> <?php echo $_POST["last"]; ?>
<br>
<?php echo $_POST["email"]; ?>
<br>
<?php echo $_POST["cell"]; ?>
<br>
<?php echo $_POST["location"]; ?>
</body>
</html>
This is a very quick solution but it should do the trick.
if ($_POST) {
$errors = null;
$error_message = "<ul>";
if (empty($_POST['first']) ||
empty($_POST['last']) ||
empty($_POST['email']) ||
empty($_POST['location'])) {
$errors = 1;
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors = 2;
}
if($errors == null) {
$to = "grimegriever#gmail.com";
$subject = "City Fitness 7-Day Pass Applicant";
$message .= "Name: ".$_POST['first']." ".$_POST['last']."\n";
$message .= "Email: ".$_POST['email']."\n";
$message .= "Cell Phone: ".$_POST['cell']."\n";
$message .= "Location: ".$_POST['location']."\n";
$from = $_POST['email'];
$headers = "From:" . $from;
mail($to, $subject, $message, $headers);
header('Location: freepass.php');
exit;
} else {
if ($errors == 1) {
$error_message .= "<li>Please fill out all fields</li>";
}
if ($errors == 2) {
$error_message .= "<li>Please enter a valid email</li>";
}
$error_message .= "</ul>";
}
}
I'm sure there are much more efficient solutions, but this will work.

strange behavior on contact form

I am having a strange problem with this form. I have made it yesterday night and it was working fine, sending all the emails as it should. However, I've run it today and it won't simply work at all. I am always getting the error message. Any clues? Thank you.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$depart = $_POST['departamento'];
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$corpo = "Nova Mensagem\n";
$corpo .= "De: " . $name . "\n";
$corpo .= "Email: " . $email . "\n";
$corpo.=" Para o departamento " . $depart. "\n";
$corpo .= "Mensagem: " . $message . "\n";
if ($depart = administrativo)
{
$email_to = '';
}
elseif ($depart = financeiro)
{
$email_to = '';
}
elseif ($depart = Suporte)
{
$email_to = '';
}
else
{
$email_to = '';
}
$status = mail($email_to, $subject, $corpo, $headers);
if($status) {
echo "<script> window.location.href = ''; </script>";
}
else {
echo "<script> window.location.href = ''; </script>";
}
?>
Instead of = use == for comparison
for example - instead of:
if( $depart = administrativo)
use
if( $depart == "administrativo" )
You should enclose strings within quotes. Moreover, == (comparing objects of different types) && === (comparing objects of same types) are used for comparing and = is used for assigning. So, change the code as follows (inside the if statements) :
if ($depart == 'administrativo')
{
$email_to = '';
}
elseif ($depart == 'financeiro')
{
$email_to = '';
}
elseif ($depart == 'Suporte')
{
$email_to = '';
}
else
{
$email_to = '';
}

Sending mail php

Hey, no idea why this sint working, but the message is being sent as "0". I think the e-mail fIELD is what is causing it
<?php
if ($_POST['check'] == 'checked'){
header("location: /nospamplease.html");
exit();
}
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$date = $_POST['date'];
$children = $_POST['children'];
$hot = $_POST['hot'];
$comments = $_POST['comments'];
/*echo $name;
echo $email;
echo $phone;
echo $date;
echo $children;
echo $hot;
echo $comments;*/
if($name == "" || $email == "" || $phone == "" || $date == "" || $children == "" || $hot == "" || $comments == ""){
echo "Please ensure all fields were filled out!";
exit();
}else{
$to = "######";
$subject = "Birthday enquiry";
$message = "Name: ".$name;
$message += "Email: ".$email;
$message += "Phone: ".$phone;
$message += "Date: ".$date;
$message += "Children: ".$children;
$message += "Hot or cold: ".$hot;
$message += "Comments: ".$comments;
//echo $message;
if(mail($to, $subject, $message)){
echo "Thank you for your enquiry, we will contact you within the next 24 hours! <br /> Click <a href='###'> here</a> to go back to the website!";
}else{
echo "There was an error, contact us directly: <a href='mailto:##'>email</a>";
}
}
?>
I echoed out the variables, they all are getting posted fine
Thanks guys
You can't use + to concatenate strings in PHP. Use .
$message .= "Email: ".$email;

Categories