Проверка контактной формы PHP не работает - PullRequest
0 голосов
/ 25 февраля 2012

У меня есть контактная форма на http://www.kaimeramedia.com/derek/Website/contact.php. Я проверил свой PHP-код на PHPcodechecker.com, и он говорит, что нет синтаксических ошибок.Я думаю, что начальный код работает в каком-то поместье, потому что каждый раз, когда я нажимаю «Отправить», он переходит к следующей проверке, на которой я остаюсь: «Обнаружен неправильный адрес электронной почты. Пожалуйста, нажмите кнопку« Назад »вашего браузера и попробуйте снова».

Я просто хочу знать, должен ли я писать код по-другому, чтобы удостовериться, что проверка электронной почты проходит и разрешить отправку сообщения.Я не уверен, что у меня есть что-то задом наперед.Я перепробовал много комбинаций, но в данный момент это самый дальний путь без ошибки mailform.php.Код для файла mailform.php:

 <?php 
     session_start();
     $dontsendemail = 0;
     $possiblespam = FALSE;
     $strlenmessage = "";
     $email = $_REQUEST['email']; 
     $name = $_REQUEST['name']; 
     $message = $_REQUEST['message']; 
     $subject = "Regarding Your Portfolio";$emailaddress = "me@website.com"; 

     // checks if name field is empty
     function checkname() {
if (empty($name)) {
    die ("You did not enter your name.  Please hit your browser back button and try again.");
return 1;
            }
        }

// checks if the captcha is input correctly
function checkcaptcha() {
            if ($_SESSION["pass"] != $_POST["userpass"]) {
                die("Sorry, you failed the CAPTCHA. Note that the CAPTCHA is case-sensitive. Please hit your browser back button and try again.");
                return 1;
            }
        }

// checks proper syntax 
function checkemail() {
    if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email));
    else{
        die("Improper email address detected. Please hit your browser back button and try again."); 
        return 1;
    }
}


function spamcheck($field) {
    if(eregi("to:",$field) || eregi("cc:",$field) || eregi("\r",$field) || eregi("\n",$field) || eregi("%0A",$field)){ 
        $possiblespam = TRUE;
    }else $possiblespam = FALSE;
    if ($possiblespam) {
        die("Possible spam attempt detected. If this is not the case, please edit the content of the contact form and try again.");
        return 1;
    }
}
function strlencheck($field,$minlength,$whichfieldresponse) {
    if (strlen($field) < $minlength){
        die($whichfieldresponse); 
        return 1;
    }



}

        if ($dontsendemail == 0) $dontsendemail = checkcaptcha($email);

if ($dontsendemail == 0) $dontsendemail = checkemail($email);
if ($dontsendemail == 0) $dontsendemail = spamcheck($email);
if ($dontsendemail == 0) $dontsendemail = spamcheck($name);
if ($dontsendemail == 0) $dontsendemail = strlencheck($email,10,"The email address field is too short. Please hit your browser back button and check your entry.<br />");
if ($dontsendemail == 0) $dontsendemail = strlencheck($message,10,"The message field is too short. Please hit your browser back button and check your entry.<br />");
if ($dontsendemail == 0) $dontsendemail = strlencheck($emailaddress,8,"You have not selected a recipient of your message. Please hit your browser back button and check your entry.<br />");
if ($dontsendemail == 0) $dontsendemail = strlencheck($name,3,"The Name field is too short. Please hit your browser back button and check your entry.<br />");
if ($dontsendemail == 0) {mail($emailaddress,"Subject: $subject",$message,"From: $name,$email" ); include "thankyou.php";}
?> 

Я поместил фиктивное письмо в этот код, но реальное - в файле mailform.php. Если кто-нибудь увидит, где я ошибся, это будеточень ценится.

Ответы [ 2 ]

2 голосов
/ 25 февраля 2012

Опираясь на мой предыдущий ответ, я полностью выложился и почистил твой сценарий.У меня явно слишком много времени на руках.Не проверял, работает ли он.Удачи!

<?PHP
session_start();
try{
    $check = new check();
    if(!isset($_REQUEST['Email']))
        throw new exception('You did not enter an email address.');

    if(!isset($_REQUEST['message']))
        throw new exception('You did not enter a message.');

    if(!isset($_REQUEST['Name']))
        throw new exception('You did not enter a name');

    $sender = $_REQUEST['Email'];
    $message = $_REQUEST['message'];
    $name = $_REQUEST['Name'];
    $recipient = 'test@test.com';

    $subject = 'Regarding Your Portfolio';

    if($check->captcha('userpass') == FALSE)
        throw new exception('Your captcha is incorrect.');

    if($check->spam($sender) == FALSE)
        throw new exception('Your email field contains spam.');

    if($check->spam($name) == FALSE)
        throw new exception('Your name field contains spam.');

    if($check->length($sender, 10) == FALSE)
        throw new exception('Your email field does not satisfy the minimum character count.');

    if($check->length($message, 8) == FALSE)
        throw new exception('Your message field does not satisfy the minimum character count.');

    if($check->length($name, 3) == FALSE)
        throw new exception('Your name field does not satisfy the minimum character count.');

    mail($recipient, $subject, $message, "From: $name <$sender>" );
    include "thankyou.php";
}catch (Exception $E){
    die($E->getMessage());
}




class check{

    function captcha($field){
        if(isset($_REQUEST[$field])==FALSE){ return false; }
        if($_SESSION['pass'] != $_REQUEST[$field]){ return false; }
        return true;
    }

    function email($email){
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ return false;}
        return true;
    }

    function spam($field){
        if(eregi("to:",$field) || eregi("cc:",$field) || eregi("\r",$field) || eregi("\n",$field) || eregi("%0A",$field)){ return false; }
        return true;
    }

    function length($field, $min){
        if(strlen($field) < $min){ return false; }
        return true;
    }
}
0 голосов
/ 25 февраля 2012

С вашим скриптом связаны две проблемы.

  1. Вы не анализируете параметр $ email. Вы забыли включить его.
  2. Регулярные выражения для электронных писем очень требовательны и не всегда включают в себя все стандарты.

Решение: Начиная с PHP5 вы можете использовать следующее для проверки электронной почты или если вы хотите использовать регулярное выражение, просто добавьте параметр $ email

function checkemail($email) {
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    }else{
        die("Improper email address detected. Please hit your browser back button and try again."); 
        return 1;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...