валидация формы обратной связи

Discussion in 'PHP' started by inc1uder, 5 Jun 2012.

  1. inc1uder

    inc1uder New Member

    Joined:
    7 Mar 2012
    Messages:
    1
    Likes Received:
    0
    Reputations:
    0
    Не стал пользоваться готовыми решениями, решил накатать сам, в целях самообразования. Просьба оценить и по возможности сказать что не так, и как исправить (оптимизировать)
    PHP:
    <?php
    $max_allowed_file_size 
    = 10240; // в размер загружаемого файла в Кб (на данный момент 10 Мб)
    $allowed_extensions    = array(
        
    "rar",
        
    "zip",
        
    "gif",
        
    "bmp",
        
    "jpeg",
        
    "jpg",
        
    "png",
        
    "txt",
        
    "rtf",
        
    "pdf"
    ); //Расширения файлов допустимые к загрузки  
    $error                 = ""; // Переменная с ошибками
    /*Формирование почты*/
    $to                    = ""; //Куда отправлять
    $bound                 = strtoupper(uniqid(time()));
    $subject               = "Заявка с сайта"; //Заголовок сообщения 
    $header                = "Mime-Version: 1.0n";
    $header .= "From:  <robot@site.ru>\r\n";
    $header .= "Content-Type: multipart/mixed;";
    $header .= "boundary=\"----------" . $bound . "\"\n\n";
    /*Меры безопасности */
    $name      = substr(strip_tags($_POST['name']), 0, 30);
    $company   = substr(strip_tags($_POST['company']), 0, 30);
    $email     = substr(strip_tags($_POST['email']), 0, 30);
    $phonecode = substr(strip_tags($_POST['phonecode']), 0, 4);
    $phone     = substr(strip_tags($_POST['phone']), 0, 8);
    $phonecode = filter_var($phonecode, FILTER_SANITIZE_NUMBER_INT);
    $phone     = filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
    $comment   = substr(strip_tags($_POST['comment']), 0, 150);

    $name      = mysql_escape_string($name);
    $company   = mysql_escape_string($company);
    $email     = mysql_escape_string($email);
    $phonecode = mysql_escape_string($phonecode);
    $phone     = mysql_escape_string($phone);
    $comment   = mysql_escape_string($comment);

    $search  = array(
        
    "'&(amp|#38);'i",
        
    "'&(lt|#60);'i",
        
    "'&(gt|#62);'i",
        
    "'&(nbsp|#160);'i",
        
    "'&(iexcl|#161);'i",
        
    "'&(cent|#162);'i",
        
    "'&(pound|#163);'i",
        
    "'&(copy|#169);'i",
        
    "'&#(\d+);'e",
        
    "'—'i",
        
    "'–'i"
    );
    $replace = array(
        
    "&",
        
    "<",
        
    ">",
        
    " ",
        
    chr(161),
        
    chr(162),
        
    chr(163),
        
    chr(169),
        
    "chr(\\1)",
        
    " - ",
        
    "-"
    );
    $email   = preg_replace($search, $replace, $email);

    if (empty(
    $email) && empty($name)) {
        
    $error .= '<br> Заполните обязательные поля';
    }
    if (
    preg_match("/[^(\w)|(\x7F-\xFF)|(\s)]/", $company) && preg_match("/[^(\w)|(\x7F-\xFF)|(\s)]/", $name)) {
        
    $error .= '<br> Название организации или имя заполнено не корректно!<br> <a href="javascript:history.go(-1)" mce_href="javascript:history.go(-1)">Вернуться</a>';
    }

    if (!
    filter_var($email, FILTER_VALIDATE_EMAIL)) {
        
    $error .= ' Проверьте правильность ввода email';
    }

    //Формирование письма.
    if (empty($error)) {
        
    $message .= '<h1>Заказ</h1>';
        
    $message .= '<table name="result" cellpadding=10 cellcpacing=10 border=1 ';
        
    $message .= '<tr><td>Имя</td><td>' . $name . '</td></tr>';
        
    $message .= '<tr><td>Организация</td><td>' . $company . '</td></tr>';
        
    $message .= '<tr><td>Контактный телефон</td><td> ( ' . $phonecode . ' )' . $phone . '</td></tr>';
        
    $message .= '<tr><td>Контактный email</td><td>' . $email . '</td></tr>';
        
    $message .= '<tr><td>Комментарий</td><td>' . $comment . '</td></tr>';
        
    $message .= '</table>';
        
    $body    = "------------" . $bound . "\nContent-Type:text/html; charset='windows-1251'\n";
        
    $body .= "Content-Transfer-Encoding: 8bit\n\n" . $message . "\n\n";

    if (
    $size_of_uploaded_file > $max_allowed_file_size) {
        
    $error .= '<br> Превышен допустимый размер файла';
    }
    $name_of_uploaded_file = basename($_FILES['file']['name']);
    $type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1);
    $size_of_uploaded_file = $_FILES["file"]["size"] / 1024;
    $allowed_ext           = false;
    for (
    $i = 0; $i < sizeof($allowed_extensions); $i++) {
        if (
    strcasecmp($allowed_extensions[$i], $type_of_uploaded_file) == 0) {
            
    $allowed_ext = true;
        }
    }
    if (!
    $allowed_ext) {
        
    $error .= "<br> Не поддерживаемый тип файла. " . " Разрешены файлы типа: " . implode(',', $allowed_extensions);
    }
    if (empty(
    $name_of_uploaded_file)){$allowed_ext= true;}
        foreach (
    $_FILES as $value) {
            if (
    $_FILES['file']['size'] != 0 && $_FILES['file']['error'] == 0) {
                
    $body .= "------------" . $bound . "\n";
                
    $body .= "Content-Type: " . $value['type'] . ";";
                
    $body .= "name=\"" . basename($value['name']) . "\"\n";
                
    $body .= "Content-Transfer-Encoding:base64\n";
                
    $body .= "Content-Disposition:attachment;";
                
    $body .= "filename=\"" . basename($value['name']) . "\"\n\n";
                
    $body .= chunk_split(base64_encode(file_get_contents($value['tmp_name']))) . "\n";
            }
            ;
        }
        
    mail($to, $subject, $body, $header);
        echo 
    "<br /><br /><center>Ваше сообщение успешно отправлено.<br />Наши менеджеры в ближайшее время свяжутся с вами для уточнения вашего заказа.<br /><br /><br />";
    } else {
        echo 
    $error;
    }
    }
    ?>