Trouble with PHP validating select box array [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am adding some new validation to a current form, I have three separate arrays that I have built for select boxes and I need to be sure that the user is making at least one of the selections. At this point when the user fills our the form, it will submit and send, but the "Required" shows next to an empty select box in the form even through the notice says it has been sent and the form will send even if the user hasn't made a selection. I have tried searching everywhere for a solution, hoping to get a second set of eyes on this issue. Thank you in advance for your time!
The select box within the form -
<?php echo $monthMessage; ?>
<select name="mm" class="select-form-style">
<option>
- Select Month -
</option>
<?php
foreach ($months as $month) {
$selected = (!empty($mm) && $mm == $month) ? 'selected="selected"' : '';
?>
<option value="<?php echo $month;?>" <?php echo $selected;?>>
<?php echo $month;?>
</option>
<?php
}
?>
The PHP form validation
<?php #Registration
$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December');
$season = array('Fall 2014', 'Winter 2014', 'Spring 2015', 'Summer 2015');
$locations = array('Priest River', 'Sandpoint', 'Online');
function makeSafe($value) {
return stripslashes(trim($value));
}
//if the form was subitted
if (!empty($_POST['submit'])) {
//form submitted through post, do validation
$authorization = (!empty($_POST['authorization'])) ? makeSafe($_POST['authorization']) : '';
$signature = (!empty($_POST['signature'])) ? makeSafe($_POST['signature']) : '';
$cc = makeSafe($_POST['cc']);
$ll = makeSafe($_POST['ll']);
$fname = makeSafe($_POST['fname']);
$mname = makeSafe($_POST['mname']);
$lname = makeSafe($_POST['lname']);
$mm = makeSafe($_POST['mm']);
$day = makeSafe($_POST['day']);
$year = makeSafe($_POST['year']);
$age = makeSafe($_POST['age']);
$school = makeSafe($_POST['school']);
$address = makeSafe($_POST['address']);
$city = makeSafe($_POST['city']);
$state = makeSafe($_POST['state']);
$zip = makeSafe($_POST['zip']);
$gender = makeSafe($_POST['gender']);
$email = makeSafe($_POST['email']);
$phone = makeSafe($_POST['phone']);
$altph = makeSafe($_POST['altph']);
$hp = makeSafe($_POST['hp']);
$packet = (!empty($_POST['signature'])) ? makeSafe($_POST['packet']) : '';
$message = '';
$problem = FALSE;
if(!empty($_POST['mm']))
{
$monthMessage .= '<p class="errorClass">Required</p>';
}
if(!empty($_POST['cc']))
{
$seasonMessage .= '<p class="errorClass">Required</p>';
}
if(!empty($_POST['ll']))
{
$locationMessage .= '<p class="errorClass">Required</p>';
}
if($_POST['authorizaton']!="1" AND $_POST['packet']!="1"){
$problem = TRUE;
$parentMessage .= '<p class="errorClass parentMsg">Please read and check the boxes below
</p>';
}
if($_POST['signature']!="1"){
$problem = TRUE;
$signatureMessage .= '<p class="errorClass">Required</p>';
}
//Check First Name
if (!eregi ('^[[:alpha:]\.\' \-]{2,}$',$fname)) {
$problem = TRUE;
$fnameMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[[:alpha:]\.\' \-]{2,}$',$lname)) {
$problem = TRUE;
$lnameMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[[:alnum:]\.\' \-]{4,}$', $school)) {
$problem = TRUE;
$schoolMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[[:alnum:]\.\' \#\-]{4,}$', $address)) {
$problem = TRUE;
$addyMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[[:alpha:]\.\' \-]{4,}$', $city)) {
$problem = TRUE;
$cityMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[[:alpha:]\.\' \-]{2,2}$', $state)) {
$problem = TRUE;
$stateMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[[:alnum:]][a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$',$email)) {
$problem = TRUE;
$emailMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[0-9]{5}(\-[0-9]{4})?$',$zip)) {
$problem = TRUE;
$zipMessage .= '<p class="errorClass">Required</p>';
}
if (!eregi ('^[0-9.\(\)\-\ ]{10,14}$', $phone)) {
$problem = TRUE;
$phoneMessage .= '<p class="errorClass">Required</p>';
}
if(!eregi('^[0-9]{2}$',$age)) {
$problem = TRUE;
$ageMessage .= '<p class="errorClass">Required</p>';
}
if(!eregi('^[0-9]{2,4}$',$year)) {
$problem = TRUE;
$yearMessage .= '<p class="errorClass">Required</p>';
}
if(!eregi('^[0-9]{1,2}$',$day)) {
$problem = TRUE;
$dayMessage .= '<p class="errorClass">Required</p>';
}
if ($problem == TRUE) {//Something went wrong
echo $message;
echo '';
}
else{
$to = "webangel119#yahoo.com";
$subject = "Buckle-Up New Student Registration";
$headers = 'From: jen.byron83#gmail.com' . "\r\n" .'X-Mailer: PHP/' . phpversion();
$msg .= "PLAIN TEXT EMAIL\n\n";
$msg .= "Location: $ll Class: $cc\n\n";
$msg .= "Name: $fname $mname $lname\n\n";
$msg .= "Birthday: $mm $day $year Age: $age Gender: $gender\n\n";
$msg .= "School: $school\n\n";
$msg .= "Address: $address\n\n";
$msg .= "City: $city State: $state Zip Code: $zip\n\n";
$msg .= "Phone: $phone Alternate Contact: $altph\n\n";
$msg .= "Email: $email\n\n";
if(mail($to, $subject, $msg, $headers) == false){
// Email failed
echo '<p>An error occured while trying to process your request</p>';
}
else {
echo '<p>Thank you for registering with Buckle-Up Driving School!</p>';
$authorization = '';
$ll = '';
$cc = '';
$fname = '';
$mname = '';
$lname = '';
$mm = '';
$day = '';
$year = '';
$age = '';
$school = '';
$address = '';
$city = '';
$state = '';
$zip = '';
$gender = '';
$email = '';
$phone = '';
$altph = '';
$hp = '';
$signature = '';
$packet = '';
}
}
}
?>

I'm not sure if i understood the problem, but if i follow my feeling about this, my answer will be :
Your mistake is up there :
if(!empty($_POST['mm']))
{
$monthMessage .= '<p class="errorClass">Required</p>';
}
So, if $_POST['mm'] is not empty, then "Required" will be shown. But you have a probleme, this value will never be empty :)
Even if no month is selected ("- Select Month -" selected), the navigator will send the content of the option tag as the value of select ;)
So you have $_POST['mm'] = "- Select Month -"
You have to do this test :
// if mm sent and is not empty
if(isset($_POST['mm']) && !empty($_POST['mm']))
{
// if mm is in $months array
if(in_array($_POST['mm'], $months))
{
// this value is not accepted or "- Select Month -" selected
}
else
{
// seems a month is selected and into your $months list
}
}
else
{
// this case happens if don't send "mm" in post
// or if the value of mm is empty
}
Btw, a value will never be sure by doing stripslashes(trim($val)); care with this.
Btw2, you can apply makeSafe() to your whole $_POST array by doing this :
foreach($_POST as $k => $v)
{
$P[$k] = makeSafe($v);
}
then call your data like $P['mm']
Hope it helped !

Related

Send learners reminder email and admin

Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?
below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}

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 ? */
}

Add a part of my form to the e-mail i receive using PHP

In my contact form i recently added a selector ( http://shopzuinig.nl/contact.html ) and styled it the way i wanted, but when i fill in the form and press send, the choice for a location is not included in the e-mail i receive. Can someone provide me with the PHP code to make this happen?
Here is my current PHP code:
<?php
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
$replyto='restaurant#dellitalia.nl';
$subject = 'Verzoek via de website';
if($post)
{
function ValidateEmail($email)
{
$regex = "/([a-z0-9_\.\-]+)". # name
"#". # at
"([a-z0-9\.\-]+){2,255}". # domain & possibly subdomains
"\.". # period
"([a-z]+){2,10}/i"; # domain extension
$eregi = preg_replace($regex, '', $email);
return empty($eregi) ? true : false;
}
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$message = stripslashes($_POST['message']);
$phone = stripslashes($_POST['phone']);
$answer = trim($_POST['answer']);
$verificationanswer="6"; // plz change edit your human answer
$from=$email;
$to=$replyto;
$error = '';
$headers= "From: $name <" . $email . "> \n";
$headers.= "Reply-to:" . $email . "\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers = "Content-Type: text/html; charset=utf-8\n".$headers;
// Checks Name Field
if(!$name || !$email || $email && !ValidateEmail($email) || $answer <> $verificationanswer || !$message || strlen($message) < 1)
{
$error .= 'De velden zijn niet correct ingevuld.<br />';
}
if(!$error)
{
$messages.="Name: $name <br>";
$messages.="Email: $email <br>";
$messages.="Message: $message <br>";
$mail = mail($to,$subject,$messages,$headers);
if($mail)
{
echo 'OK';
if($autorespond == "yes")
{
include("autoresponde.php");
}
}
}
else
{
echo '<div class="error">'.$error.'</div>';
}
}
?>
Location Missing in your message. Include location to get location details in your mail.
if(!$error)
{
$mydropdown=$_POST['mydropdown'];
$mydropdown=mysql_real_escape_string($mydropdown);
$messages.="Name: $name <br>";
$messages.="Email: $email <br>";
$messages.="Message: $message <br>";
$messages.="Location: $mydropdown<br>"; // Missing. Include Location Here
$mail = mail($to,$subject,$messages,$headers);
if($mail)
{
echo 'OK';
if($autorespond == "yes")
{
include("autoresponde.php");
}
}
}

PHP Mail form not generating mail [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 8 years ago.
OK, my php email script is hosted on another server to my form. It has worked fine until recently, but a couple of unrelated changes seem to have buggered things up. I think I have an idea what might be going on, but let me explain the problem first.
At first I thought it was an issue with depricated !eregi commands. So, I changed them all to !preg_match, but that apparently wasn't the only issue.
The form appears to work, there are no errors being reported, and the success page is parsing, but no email is ever sent (yes, I checked my spam folder). Around the same time the issues started, I moved the website and domain that the original php mail script is hosted on to a different server that (one that I can't host php files on), but kept the php mail script on the old server. Of course, without the domain pointing to that web server the external referencing stopped working. So, I just dropped the file into a subdomain on the old server, and re-referenced the form accordingly. It now connects fine, and as I said, parses the script through to the success page.
The email hosting for this server was never changed. So, ththere shouldn't be an issue, but I think the problem is related to that domain name change. Any thoughts? Script and form address below:
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
if(isset($_POST['email'])) {
// set the EMAIL TO options
$email_to = "jr#creativeheat.co.uk";
$email_bcc = "jr#creativeheat.co.uk";
$email_subject = "Website booking inquiry";
// grab referal info from POST
$path = explode('/', $_SERVER['HTTP_REFERER']);
$referer = $path[2];
// redirect to error page
function died($error) {
$path = explode('/', $_SERVER['HTTP_REFERER']);
$referer = $path[2];
header( 'Location: http://'.$referer.'/'.$error ) ;
exit;
}
// grab the checkbox values and change them to strings
if (isset($_POST['booking_0'])) { $book1 = $_POST['booking_0']; if( $book1 == 'Bedroom(s)') { $book1 = " The Bedroom(s) \n"; }} else {$book1 = "\n";}
if (isset($_POST['booking_1'])) { $book2 = $_POST['booking_1']; if( $book2 == 'Meeting Room') { $book2 = " The Meeting Room \n";}} else {$book2 = "\n";}
if (isset($_POST['booking_2'])) { $book3 = $_POST['booking_2']; if( $book3 == 'Barn') { $book3 = " The Barn \n"; }} else {$book3 = "\n";}
if (isset($_POST['booking_3'])) { $book4 = $_POST['booking_3']; if( $book4 == 'Campsite') { $book4 = " The Campsite \n";}} else {$book4 = "\n";}
// clear the ERRORTYPE & ERROR_MESSAGE variables
$errortype = "";
$error_message = "";
// then check for an all false in the checkbox group
if (!isset($_POST['booking_0']) && !isset($_POST['booking_1']) && !isset($_POST['booking_2']) && !isset($_POST['booking_3'])) {
// provided none of the checkboxes are ticked set the DIED function parameter to ERRORTYPE = BOOKINGERR
$error_message = 'error';
$errortype = 'bookingerr';
if(strlen($error_message) > 0) {
died($errortype) ;
}
// alternate bruteforce redirect to NO BOOKING TYPE SELECTED page
// header( 'Location: http://'.$referer.'/booking/'.$errortype ) ;
}
// check everything else
// reset the ERROR variables
$errortype = "";
$error_message = "";
// check the ISSET state of the remaining required fields
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['number']) ||
!isset($_POST['email']) ||
!isset($_POST['adults']) ||
!isset($_POST['children']) ||
!isset($_POST['from_date']) ||
!isset($_POST['to_date']) ||
!isset($_POST['disabled']) ||
!isset($_POST['parking']) ||
!isset($_POST['general'])) {
// redirect to GENERAL INVALIDATION page
$error_message = 'error';
$errortype = 'requirederror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
// set FIELD variables
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$telephone = $_POST['number']; // required
$email_from = $_POST['email']; // required
$adults = $_POST['adults']; // required
$children = $_POST['children']; // required
$fdate = $_POST['from_date']; // required
$tdate = $_POST['to_date']; // required
$disabled = $_POST['disabled']; // not required
$parking = $_POST['parking']; // not required
$comments = $_POST['general']; // not required
// begin INVALID field character checks
$email_exp = "/^[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i";
$errortype = "";
$error_message = "";
if(!preg_match($email_exp,$email_from)) {
// redirect to INVALID EMAIL page
$error_message = 'error';
$errortype = 'emailinvalid';
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$string_exp = "/^[a-z .'-]+$/i";
$errortype = "";
$error_message = "";
if(!preg_match($string_exp,$first_name)) {
// redirect to INVALID FIRSTNAME page
$error_message = 'error';
$errortype = 'fnameerror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$errortype = "";
$error_message = "";
if(!preg_match($string_exp,$last_name)) {
// redirect to INVALID LASTNAME page
$error_message = 'error';
$errortype = 'lnameerror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$errortype = "";
$error_message = "";
if(strlen($comments) < 2 && strlen($comments) > 0) {
// redirect to INVALID COMMENTS page
$error_message = 'error';
$errortype = 'commentserror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$string_exp = "/^[0-9 .-]+$/i";
$errortype = "";
$error_message = "";
if(!preg_match($string_exp,$telephone)) {
// redirect to INVALID TELEPHONE page
$error_message = 'error';
$errortype = 'telephoneerror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
// failsafe
if(strlen($error_message) > 0) {
died($errortype) ;
}
// begin EMAIL MESSAGE creation
$email_message = "Form details below.\n\n";
// remove ILLEGAL data from submitted fields
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
// set EMAIL_MESSAGE variable from data gathered from form
$email_message .= "Name: ".clean_string($first_name)." ".clean_string($last_name)."\n";
$email_message .= "Contact number: ".clean_string($telephone)."\n";
$email_message .= "Email address: ".clean_string($email_from)."\n\n";
$email_message .= "Interested in availability of the following: \n";
$email_message .= $book1.$book2.$book3.$book4."\n";
$email_message .= "Date from: ".clean_string($fdate)."\n";
$email_message .= "Date to: ".clean_string($tdate)."\n\n";
$email_message .= "Number of...\n";
$email_message .= "Adults: ".clean_string($adults)."\n";
$email_message .= "Children: ".clean_string($children)."\n\n";
$email_message .= "Disabled? ".clean_string($disabled)."\n";
$email_message .= "Parking? ".clean_string($parking)."\n\n";
$email_message .= "Additional Information: \n\n";
$email_message .= clean_string($comments);
// create EMAIL HEADERS
$headers = 'From: '.$email_from."\r\n".'Reply-To: '.$email_from."\r\n".'Bcc: '.$email_bcc."\r\n".'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
// redirect to SUCCESS page
header( 'Location: http://'.$referer.'/success' ) ;
exit;
}
?>
form address: http://www.claverhammeetinghouse.org.uk/booking/
EDIT:
After installing PHPmailer the code now looks like this:
<?php
// new
require_once('class.phpmailer.php');
//end new
ini_set("display_errors", "1");
error_reporting(E_ALL);
if(isset($_POST['email'])) {
// set the EMAIL TO options
$email_to = "jr#creativeheat.co.uk";
$email_bcc = "jr#creativeheat.co.uk";
$email_subject = "Website booking inquiry";
// grab referal info from POST
$path = explode('/', $_SERVER['HTTP_REFERER']);
$referer = $path[2];
// redirect to error page
function died($error) {
$path = explode('/', $_SERVER['HTTP_REFERER']);
$referer = $path[2];
header( 'Location: http://'.$referer.'/'.$error ) ;
exit;
}
// grab the checkbox values and change them to strings
if (isset($_POST['booking_0'])) { $book1 = $_POST['booking_0']; if( $book1 == 'Bedroom(s)') { $book1 = " The Bedroom(s) \n"; }} else {$book1 = "\n";}
if (isset($_POST['booking_1'])) { $book2 = $_POST['booking_1']; if( $book2 == 'Meeting Room') { $book2 = " The Meeting Room \n";}} else {$book2 = "\n";}
if (isset($_POST['booking_2'])) { $book3 = $_POST['booking_2']; if( $book3 == 'Barn') { $book3 = " The Barn \n"; }} else {$book3 = "\n";}
if (isset($_POST['booking_3'])) { $book4 = $_POST['booking_3']; if( $book4 == 'Campsite') { $book4 = " The Campsite \n";}} else {$book4 = "\n";}
// clear the ERRORTYPE & ERROR_MESSAGE variables
$errortype = "";
$error_message = "";
// then check for an all false in the checkbox group
if (!isset($_POST['booking_0']) && !isset($_POST['booking_1']) && !isset($_POST['booking_2']) && !isset($_POST['booking_3'])) {
// provided none of the checkboxes are ticked set the DIED function parameter to ERRORTYPE = BOOKINGERR
$error_message = 'error';
$errortype = 'bookingerr';
if(strlen($error_message) > 0) {
died($errortype) ;
}
// alternate bruteforce redirect to NO BOOKING TYPE SELECTED page
// header( 'Location: http://'.$referer.'/booking/'.$errortype ) ;
}
// check everything else
// reset the ERROR variables
$errortype = "";
$error_message = "";
// check the ISSET state of the remaining required fields
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['number']) ||
!isset($_POST['email']) ||
!isset($_POST['adults']) ||
!isset($_POST['children']) ||
!isset($_POST['from_date']) ||
!isset($_POST['to_date']) ||
!isset($_POST['disabled']) ||
!isset($_POST['parking']) ||
!isset($_POST['general'])) {
// redirect to GENERAL INVALIDATION page
$error_message = 'error';
$errortype = 'requirederror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
// set FIELD variables
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$telephone = $_POST['number']; // required
$email_from = $_POST['email']; // required
$adults = $_POST['adults']; // required
$children = $_POST['children']; // required
$fdate = $_POST['from_date']; // required
$tdate = $_POST['to_date']; // required
$disabled = $_POST['disabled']; // not required
$parking = $_POST['parking']; // not required
$comments = $_POST['general']; // not required
// begin INVALID field character checks
$email_exp = "/^[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i";
$errortype = "";
$error_message = "";
if(!preg_match($email_exp,$email_from)) {
// redirect to INVALID EMAIL page
$error_message = 'error';
$errortype = 'emailinvalid';
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$string_exp = "/^[a-z .'-]+$/i";
$errortype = "";
$error_message = "";
if(!preg_match($string_exp,$first_name)) {
// redirect to INVALID FIRSTNAME page
$error_message = 'error';
$errortype = 'fnameerror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$errortype = "";
$error_message = "";
if(!preg_match($string_exp,$last_name)) {
// redirect to INVALID LASTNAME page
$error_message = 'error';
$errortype = 'lnameerror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$errortype = "";
$error_message = "";
if(strlen($comments) < 2 && strlen($comments) > 0) {
// redirect to INVALID COMMENTS page
$error_message = 'error';
$errortype = 'commentserror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
$string_exp = "/^[0-9 .-]+$/i";
$errortype = "";
$error_message = "";
if(!preg_match($string_exp,$telephone)) {
// redirect to INVALID TELEPHONE page
$error_message = 'error';
$errortype = 'telephoneerror' ;
if(strlen($error_message) > 0) {
died($errortype) ;
}
}
// failsafe
if(strlen($error_message) > 0) {
died($errortype) ;
}
// begin EMAIL MESSAGE creation
$email_message = "Form details below.\n\n";
// remove ILLEGAL data from submitted fields
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
// set EMAIL_MESSAGE variable from data gathered from form
$email_message .= "Name: ".clean_string($first_name)." ".clean_string($last_name)."\n";
$email_message .= "Contact number: ".clean_string($telephone)."\n";
$email_message .= "Email address: ".clean_string($email_from)."\n\n";
$email_message .= "Interested in availability of the following: \n";
$email_message .= $book1.$book2.$book3.$book4."\n";
$email_message .= "Date from: ".clean_string($fdate)."\n";
$email_message .= "Date to: ".clean_string($tdate)."\n\n";
$email_message .= "Number of...\n";
$email_message .= "Adults: ".clean_string($adults)."\n";
$email_message .= "Children: ".clean_string($children)."\n\n";
$email_message .= "Disabled? ".clean_string($disabled)."\n";
$email_message .= "Parking? ".clean_string($parking)."\n\n";
$email_message .= "Additional Information: \n\n";
$email_message .= clean_string($comments);
// create EMAIL HEADERS
$headers = 'From: '.$email_from."\r\n".'Reply-To: '.$email_from."\r\n".'Bcc: '.$email_bcc."\r\n".'X-Mailer: PHP/' . phpversion();
//new
new PHPMailer($email_to, $email_subject, $email_message, $headers);
//end new
// old #mail($email_to, $email_subject, $email_message, $headers);
//end old
// redirect to SUCCESS page
header( 'Location: http://'.$referer.'/success' ) ;
exit;
}
?>
Try using only "\n" instead of "\r\n" on $headers as documented in the PHP reference. http://php.net/manual/de/function.mail.php

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 = '';
}

Categories