Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770
Форумы портала PHP.SU :: Версия для печати :: Не загружаются фото формата .jpeg
Форумы портала PHP.SU » » Вопросы новичков » Не загружаются фото формата .jpeg

Страниц (1): [1]
 

1. fantast - 04 Сентября, 2018 - 21:31:25 - перейти к сообщению
Всем доброго времени суток.
При загрузке фото расширения .jpeg вылазит сообщение что тип файла wd3r2de.jpeg не соответствует разрешенному. Если я убираю в конце имени файла расширение .jpeg и заменяю на .jpg то фото загружается, если оставляю только название фото без расширения - также загружается. То есть, фото не загружается если в конце имени указано расширение .jpeg .JPEG
Подозреваю, что проблема именно в этой проверке:
CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. ProcessForm.prototype.validateFileExtension = function (filename) {
  3.         // получаем расширение файла
  4.         var fileExtension = filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
  5.         // если есть расширение, то проверяем соотвествует ли оно допустимому
  6.         if (fileExtension) {
  7.             for (var i = 0; i <= this.validFileExtensions.length; i++) {
  8.                 if (this.validFileExtensions[i] === fileExtension.toLowerCase()) {
  9.                     return true;
  10.                 }
  11.             }
  12.         }
  13.         return false;
  14.     };
  15.  

Весь код:
PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. // подключаем файл настроек
  5. require_once dirname(__FILE__) . '/process_settings.php';
  6.  
  7. // открываем сессию
  8.  
  9. // переменная, хранящая основной статус обработки формы
  10. $data['result'] = 'success';
  11.  
  12. // функция для проверки количество символов в тексте
  13. function checkTextLength($text, $minLength, $maxLength)
  14. {
  15.     $result = false;
  16.     $textLength = mb_strlen($text, 'UTF-8');
  17.     if (($textLength >= $minLength) && ($textLength <= $maxLength)) {
  18.         $result = true;
  19.     }
  20.     return $result;
  21. }
  22.  
  23. // обрабатывать будем только ajax запросы
  24. if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
  25.     exit();
  26. }
  27. // обрабатывать данные будет только если они посланы методом POST
  28. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  29.     exit();
  30. }
  31.  
  32. // валидация формы
  33.  
  34. // валидация поля name
  35. if (isset($_POST['name'])) {
  36.     $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); // защита от XSS
  37.     if (!checkTextLength($name, 4, 20)) { // проверка на количество символов в тексте
  38.         $data['name'] = 'Поле <b>Имя</b> содержит недопустимое количество символов';
  39.         $data['result'] = 'error';
  40.     }
  41. } else {
  42.     $data['name'] = 'Поле <b>Имя</b> не заполнено';
  43.     $data['result'] = 'error';
  44. }
  45.  
  46. // валидация поля family
  47. if (isset($_POST['family'])) {
  48.     $family = filter_var($_POST['family'], FILTER_SANITIZE_STRING); // защита от XSS
  49.     if (!checkTextLength($family, 4, 20)) { // проверка на количество символов в тексте
  50.         $data['family'] = 'Поле <b>Имя</b> содержит недопустимое количество символов';
  51.         $data['result'] = 'error';
  52.     }
  53. } else {
  54.     $data['family'] = 'Поле <b>Фамилия</b> не заполнено';
  55.     $data['result'] = 'error';
  56. }
  57. //валидация поля email
  58. if (isset($_POST['email'])) {
  59.     if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { // защита от XSS
  60.         $data['email'] = 'Поле <b>Email</b> имеет не корректный адрес';
  61.         $data['result'] = 'error';
  62.     } else {
  63.         $email = $_POST['email'];
  64.     }
  65. } else {
  66.     $data['email'] = 'Поле <b>Email</b> не заполнено';
  67.     $data['result'] = 'error';
  68. }
  69. // валидация поля telephone
  70. if (isset($_POST['telephone'])) {
  71.     $telephone = filter_var($_POST['telephone'], FILTER_SANITIZE_STRING); // защита от XSS
  72.     if (!checkTextLength($telephone, 9, 18)) { // проверка на количество символов в тексте
  73.         $data['telephone'] = 'Поле <b>Номер телефона</b> содержит недопустимое количество символов';
  74.         $data['result'] = 'error';
  75.     }
  76. } else {
  77.     $data['telephone'] = 'Поле <b>Номер телефона</b> не заполнено';
  78.     $data['result'] = 'error';
  79. }
  80. // валидация поля card
  81. //if (isset($_POST['card'])) {
  82. //    $card = filter_var($_POST['card'], FILTER_SANITIZE_STRING); // защита от XSS
  83. //    if (!checkTextLength($card, 16, 20)) { // проверка на количество символов в тексте
  84. //        $data['card'] = 'Поле <b>Карта ПриватБанк</b> содержит недопустимое количество символов';
  85. //        $data['result'] = 'error';
  86. //    }
  87. //} else {
  88. //    $data['card'] = 'Поле <b>Карта ПриватБанк</b> не заполнено';
  89. //    $data['result'] = 'error';
  90. //}
  91. // валидация поля city
  92. if (isset($_POST['city'])) {
  93.     $city = filter_var($_POST['city'], FILTER_SANITIZE_STRING); // защита от XSS
  94.     if (!checkTextLength($city, 4, 15)) { // проверка на количество символов в тексте
  95.         $data['city'] = 'Поле <b>Город</b> содержит недопустимое количество символов';
  96.         $data['result'] = 'error';
  97.     }
  98. } else {
  99.     $data['city'] = 'Поле <b>Город</b> не заполнено';
  100.     $data['result'] = 'error';
  101. }
  102. //валидация поля message
  103. if (isset($_POST['message'])) {
  104.     $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING); // защита от XSS
  105.     if (!checkTextLength($message, 5, 100)) { // проверка на количество символов в тексте
  106.         $data['message'] = 'Поле <b>Сообщение</b> содержит недопустимое количество символов';
  107.         $data['result'] = 'error';
  108.     }
  109. } else {
  110.     $data['message'] = 'Поле <b>Сообщение</b> не заполнено';
  111.     $data['result'] = 'error';
  112. }
  113.  
  114.  
  115.  
  116. // валидация файлов
  117. if (isset($_FILES['attachment'])) {
  118.     // перебор массива $_FILES['attachment']
  119.     foreach ($_FILES['attachment']['error'] as $key => $error) {
  120.         // если файл был успешно загружен на сервер (ошибок не возникло), то...
  121.         if ($error == UPLOAD_ERR_OK) {
  122.             // получаем имя файла
  123.             $fileName = $_FILES['attachment']['name'][$key];
  124.             // получаем расширение файла в нижнем регистре
  125.             $fileExtension = mb_strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  126.             // получаем размер файла
  127.             $fileSize = $_FILES['attachment']['size'][$key];
  128.             // результат проверки расширения файла
  129.             $resultCheckExtension = true;
  130.             // проверяем расширение загруженного файла
  131.             if (!in_array($fileExtension, $allowedExtensions)) {
  132.                 $resultCheckExtension = false;
  133.                 $data['info'][] = 'Тип файла ' . $fileName . ' не соответствует разрешенному';
  134.                 $data['result'] = 'error';
  135.             }
  136.             // проверяем размер файла
  137.             if ($resultCheckExtension && ($fileSize > MAX_FILE_SIZE)) {
  138.                 $data['info'][] = 'Размер файла ' . $fileName . ' превышает 50 Мбайт';
  139.                 $data['result'] = 'error';
  140.             }
  141.         }
  142.     }
  143.     // если ошибок валидации не возникло, то...
  144.     if ($data['result'] == 'success') {
  145.         // переменная для хранения имён файлов
  146.         $attachments = array();
  147.         // перемещение файлов в директорию UPLOAD_PATH
  148.         foreach ($_FILES['attachment']['name'] as $key => $attachment) {
  149.             // получаем имя файла
  150.             $fileName = basename($_FILES['attachment']['name'][$key]);
  151.             // получаем расширение файла в нижнем регистре
  152.             $fileExtension = mb_strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
  153.             // временное имя файла на сервере
  154.             $fileTmp = $_FILES['attachment']['tmp_name'][$key];
  155.             // создаём уникальное имя
  156.             $fileNewName = uniqid('upload_', true) . '.' . $fileExtension;
  157.             // перемещаем файл в директорию
  158.             if (!move_uploaded_file($fileTmp, $uploadPath . $fileNewName)) {
  159.                 // ошибка при перемещении файла
  160.                 $data['info'][] = 'Ошибка при загрузке файлов';
  161.                 $data['result'] = 'error';
  162.             } else {
  163.                 $attachments[] = $uploadPath . $fileNewName;
  164.             }
  165.         }
  166.     }
  167. }
  168.  
  169.  
  170. // отправка формы (данных на почту)
  171. if ($data['result'] == 'success') {
  172.     // включить файл PHPMailerAutoload.php
  173.     require_once('../phpmailer/PHPMailerAutoload.php');
  174.  
  175.     //формируем тело письма
  176.     $bodyMail = file_get_contents('email.tpl'); // получаем содержимое email шаблона
  177.  
  178.     // добавление файлов в виде ссылок
  179.     if (isset($attachments)) {
  180.         $listFiles = '<ul>';
  181.         foreach ($attachments as $attachment) {
  182.             $fileHref = substr($attachment, strpos($attachment, 'feedback/uploads/'));
  183.             $fileName = basename($fileHref);
  184.             $listFiles .= '<li><a href="' . $startPath . $fileHref . '">' . $fileName . '</a></li>';
  185.         }
  186.         $listFiles .= '</ul>';
  187.         $bodyMail = str_replace('%email.attachments%', $listFiles, $bodyMail);
  188.     } else {
  189.         $bodyMail = str_replace('%email.attachments%', '-', $bodyMail);
  190.     }
  191.  
  192.     // выполняем замену плейсхолдеров реальными значениями
  193.     $bodyMail = str_replace('%email.title%', MAIL_SUBJECT, $bodyMail);
  194.     $bodyMail = str_replace('%email.nameuser%', isset($name) ? $name : '-', $bodyMail);
  195.     $bodyMail = str_replace('%email.familyuser%', isset($family) ? $family : '-', $bodyMail);
  196.     $bodyMail = str_replace('%email.telephoneuser%', isset($telephone) ? $telephone : '-', $bodyMail);
  197.     //$bodyMail = str_replace('%email.carduser%', isset($card) ? $card : '-', $bodyMail);
  198.     $bodyMail = str_replace('%email.cityuser%', isset($city) ? $city : '-', $bodyMail);
  199.     $bodyMail = str_replace('%email.message%', isset($message) ? $message : '-', $bodyMail);
  200.     $bodyMail = str_replace('%email.emailuser%', isset($email) ? $email : '-', $bodyMail);
  201.     $bodyMail = str_replace('%email.date%', date('d.m.Y H:i'), $bodyMail);
  202.  
  203.     // отправляем письмо с помощью PHPMailer
  204.     $mail = new PHPMailer;
  205.     $mail->CharSet = 'UTF-8';
  206.     $mail->IsHTML(true);  // формат HTML
  207.     $fromName = '=?UTF-8?B?'.base64_encode(MAIL_FROM_NAME).'?=';
  208.     $mail->setFrom(MAIL_FROM, $fromName);
  209.     $mail->Subject = '=?UTF-8?B?'.base64_encode(MAIL_SUBJECT).'?=';
  210.     $mail->Body = $bodyMail;
  211.     $mail->addAddress(MAIL_ADDRESS);
  212.  
  213.     // прикрепление файлов к письму
  214.     if (isset($attachments)) {
  215.         foreach ($attachments as $attachment) {
  216.             $mail->addAttachment($attachment);
  217.         }
  218.     }
  219.  
  220.     // отправляем письмо
  221.     if (!$mail->send()) {
  222.         $data['result'] = 'error';
  223.     }
  224.  
  225.     // информируем пользователя по email о доставке
  226.     if (isset($email)) {
  227.         // очистка всех адресов и прикреплёных файлов
  228.         $mail->clearAllRecipients();
  229.         $mail->clearAttachments();
  230.         //формируем тело письма
  231.         $bodyMail = file_get_contents('email_client.tpl'); // получаем содержимое email шаблона
  232.         // выполняем замену плейсхолдеров реальными значениями
  233.         $bodyMail = str_replace('%email.title%', MAIL_SUBJECT, $bodyMail);
  234.         $bodyMail = str_replace('%email.nameuser%', isset($name) ? $name : '-', $bodyMail);
  235.         $bodyMail = str_replace('%email.date%', date('d.m.Y H:i'), $bodyMail);
  236.         $mail->Subject = MAIL_SUBJECT_CLIENT;
  237.         $mail->Body = $bodyMail;
  238.         $mail->addAddress($email);
  239.         $mail->send();
  240.     }
  241. }
  242.  
  243. // отправка данных формы в файл
  244. if ($data['result'] == 'success') {
  245.     $name = isset($name) ? $name : '-';
  246.     $family = isset($family) ? $family : '-';
  247.     $telephone = isset($telephone) ? $telephone : '-';
  248.     //$card = isset($card) ? $card : '-';
  249.     $city = isset($city) ? $city : '-';
  250.     $email = isset($email) ? $email : '-';
  251.     $message = isset($message) ? $message : '-';
  252.     $output = "---------------------------------" . "\n";
  253.     $output .= date("d-m-Y H:i:s") . "\n";
  254.     $output .= "Имя пользователя: " . $name . "\n";
  255.     $output .= "Фамилия пользователя: " . $family . "\n";
  256.     $output .= "Номер телефона: " . $telephone . "\n";
  257.     $output .= "Город: " . $city . "\n";
  258.    // $output .= "Карта: " . $card . "\n";
  259.     $output .= "Адрес email: " . $email . "\n";
  260.     $output .= "Сообщение: " . $message . "\n";
  261.     if (isset($attachments)) {
  262.         $output .= "Файлы: " . "\n";
  263.         foreach ($attachments as $attachment) {
  264.             $output .= $attachment . "\n";
  265.         }
  266.     }
  267.     if (!file_put_contents(dirname(dirname(__FILE__)) . '/info/message.txt', $output, FILE_APPEND | LOCK_EX)) {
  268.         $data['result'] = 'error';
  269.     }
  270. }
  271.  
  272. // сообщаем результат клиенту
  273. echo json_encode($data);
  274.  
  275.  

Main.js
CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. "use strict";
  3.  
  4. //после загрузки веб-страницы
  5. $(function () {
  6.  
  7.     var ProcessForm = function (parameters) {
  8.  
  9.         // id формы обратной связи
  10.         this.idForm = parameters['idForm'] || 'feedbackForm';
  11.         // скрыть форму после отправки
  12.         this.hideForm = parameters['hideForm'] || true;
  13.         // наличие у формы блока загрузки файлов
  14.         this.existenceUploadsFile = parameters['existenceUploadsFile'] || true;
  15.         // наличие у формы капчи
  16.         this.existenceCaptcha = parameters['existenceCaptcha'] || false;
  17.         // количество элементов input для загрузки файлов
  18.         this.countFiles = parameters['countFiles'] || 4;
  19.         // максимальный размер файла для загрузки (по умолчанию 512 Кбайт)
  20.         this.maxSizeFile = parameters['maxSizeFile'] || 5242880;
  21.         // допустимые разрешения файлов
  22.         this.validFileExtensions = parameters['validFileExtensions'] || ['jpg', 'jpeg', 'bmp', 'gif', 'png'];
  23.         // флажок о принятии пользовательского соглашения перед отправкой формы
  24.         this.disableAgreement = parameters['disableAgreement'] || false;
  25.  
  26.         // инициализация
  27.         this.init = function () {
  28.             // получаем форму
  29.             var submitForm = document.getElementById(this.idForm);
  30.             // отправка формы
  31.             $(submitForm).submit($.proxy(this.submitForm, this));
  32.             if (this.existenceCaptcha) {
  33.                 // обновление капчи
  34.                 $(submitForm).find('.refresh-captcha').click($.proxy(this.refreshCaptcha, this));
  35.             }
  36.  
  37.             if (this.existenceUploadsFile) { // добавление новых элементов input с type="file" и изменение существующих
  38.                 $('#' + this.idForm + ' .countFiles').text(this.countFiles);
  39.                 // добавление нового элемента input с type="file"
  40.                 $(document).on('change', '#' + this.idForm + ' input[name="attachment[]"]', $.proxy(this.changeInputFile, this));
  41.             }
  42.  
  43.             if (!this.disableAgreement) {
  44.                 $(document).on('change', '#' + this.idForm + ' input[name="agree"]', $.proxy(this.changeAgreement, this));
  45.             }
  46.  
  47.             if (this.hideForm) {
  48.                 var self = this;
  49.                 $(submitForm).parent().find('.show-form').click(function (e) {
  50.                     e.preventDefault();
  51.                     $(this).closest('.success-message').addClass('hidden');
  52.                     if (self.disableAgreement) {
  53.                         self.changeStateSubmit(false);
  54.                     }
  55.                     $(submitForm).show();
  56.                 });
  57.             }
  58.         };
  59.     };
  60.  
  61.     // переключить во включенное или выключенное состояние кнопку submit
  62.     ProcessForm.prototype.changeStateSubmit = function (state) {
  63.         var submitForm = document.getElementById(this.idForm);
  64.         $(submitForm).find('[type="submit"]').prop('disabled', state);
  65.     };
  66.  
  67.     // изменение состояния кнопки submit в зависимости от состояния checkbox agree
  68.     ProcessForm.prototype.changeAgreement = function (e) {
  69.         if (e.currentTarget.checked) {
  70.             this.changeStateSubmit(false);
  71.         } else {
  72.             this.changeStateSubmit(true);
  73.         }
  74.     };
  75.  
  76.     // метод, возвращающий результат проверки расширения файла допустимому
  77.     ProcessForm.prototype.validateFileExtension = function (filename) {
  78.         // получаем расширение файла
  79.         var fileExtension = filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
  80.         // если есть расширение, то проверяем соотвествует ли оно допустимому
  81.         if (fileExtension) {
  82.             for (var i = 0; i <= this.validFileExtensions.length; i++) {
  83.                 if (this.validFileExtensions[i] === fileExtension.toLowerCase()) {
  84.                     return true;
  85.                 }
  86.             }
  87.         }
  88.         return false;
  89.     };
  90.  
  91.     // валилация формы
  92.     ProcessForm.prototype.validateForm = function () {
  93.         var _this = this;
  94.         var validForm = true;
  95.         var submitForm = document.getElementById(this.idForm);
  96.         $(submitForm).find('input,textarea').each(function () {
  97.             if (this.checkValidity()) {
  98.                 _this.changeStateInput(this, 'success');
  99.             } else {
  100.                 _this.changeStateInput(this, 'error');
  101.                 $.jGrowl('Поле: "<strong>' + $(this).parent().find('label').text() + '</strong>"<br>' + this.validationMessage, {
  102.                     theme: 'jgrowl-error',
  103.                     life: 10000
  104.                 });
  105.                 validForm = false;
  106.             }
  107.         });
  108.         return validForm;
  109.     };
  110.  
  111.     // изменение состояния элемента формы (success, error, clear)
  112.     ProcessForm.prototype.changeStateInput = function (input, state) {
  113.         input = $(input);
  114.         var inputGroup = input.parents('.form-group');
  115.         var glyphiconInput = inputGroup.find('.form-control-feedback');
  116.         if (state === 'error') {
  117.             inputGroup.removeClass('has-success').addClass('has-error');
  118.             if (input.prop("tagName").toLowerCase() !== 'textarea') {
  119.                 glyphiconInput.removeClass('glyphicon-ok').addClass('glyphicon-remove');
  120.             }
  121.         } else if (state === 'success') {
  122.             inputGroup.removeClass('has-error').addClass('has-success');
  123.             if (input.prop("tagName").toLowerCase() !== 'textarea') {
  124.                 glyphiconInput.removeClass('glyphicon-remove').addClass('glyphicon-ok');
  125.             }
  126.         } else {
  127.             inputGroup.removeClass('has-success has-error');
  128.             glyphiconInput.removeClass('glyphicon-ok glyphicon-remove');
  129.         }
  130.     };
  131.  
  132.     // disabled и enabled изображений для FormData
  133.     ProcessForm.prototype.changeStateImages = function (state) {
  134.         if (!this.existenceUploadsFile) {
  135.             return;
  136.         }
  137.         var submitForm = document.getElementById(this.idForm);
  138.         var files = $(submitForm).find('[name="attachment[]"]');
  139.         for (var i = 0; i < files.length; i++) {
  140.             // получить список файлов элемента input с type="file"
  141.             var fileList = files[i].files;
  142.             // если элемент не содержит файлов, то перейти к следующему
  143.             if (fileList.length > 0) {
  144.                 // получить первый файл из списка
  145.                 var file = fileList[0];
  146.                 // проверить тип файла и размер
  147.                 if (!((this.validateFileExtension(file.name)) && (file.size < this.maxSizeFile))) {
  148.                     $(files[i]).prop('disabled', state);
  149.                 }
  150.             } else {
  151.                 $(files[i]).prop('disabled', state);
  152.             }
  153.         }
  154.     };
  155.  
  156.     // сбор данных для отправки на сервер с помощью FormData
  157.     ProcessForm.prototype.collectData = function () {
  158.         this.changeStateImages(true); // отключаем отправку файлов (disabled) не удовлетворяющие требованиям
  159.         this.dataForm = new FormData(document.getElementById(this.idForm)); // собираем данные
  160.         this.changeStateImages(false); // после сбора данных переводим состояние элементов в enabled
  161.     };
  162.  
  163.     // отправка формы
  164.     ProcessForm.prototype.submitForm = function (e) {
  165.         var _this = this;
  166.         e.preventDefault();
  167.         if (this.validateForm() === false) {
  168.           return;
  169.         }
  170.         this.collectData();
  171.         $.ajax({
  172.             type: "POST",
  173.             url: $('#' + _this.idForm).attr('action'),
  174.             data: _this.dataForm, // данные для отправки на сервер
  175.             contentType: false,
  176.             processData: false,
  177.             cache: false,
  178.             beforeSend: function () {
  179.                 $('#' + _this.idForm + ' .progress').show();
  180.                  _this.changeStateSubmit(true);
  181.             },
  182.  
  183.             xhr: function () {
  184.                 var myXhr = $.ajaxSettings.xhr();
  185.                 if (myXhr.upload) {
  186.                     myXhr.upload.addEventListener('progress', function (event) {
  187.                         // если известно количество байт для пересылки
  188.                         if (event.lengthComputable) {
  189.                             // получаем общее количество байт для пересылки
  190.                             var total = event.total;
  191.                             // получаем какое количество байт уже отправлено
  192.                             var loaded = event.loaded;
  193.                             // определяем процент отправленных данных на сервер
  194.                             var progress = ((loaded * 100) / total).toFixed(1);
  195.                             // обновляем состояние прогресс бара Bootstrap
  196.                             var progressBar = $('#' + _this.idForm + ' .progress-bar');
  197.                             progressBar.attr('aria-valuenow', progress);
  198.                             progressBar.width(progress + '%');
  199.                             progressBar.find('span').text(progress + '%');
  200.                         }
  201.                     }, false);
  202.                 }
  203.                 return myXhr;
  204.             },
  205.  
  206.  
  207.             success: function (data) {
  208.                 $('#' + _this.idForm + ' .progress').hide();
  209.  
  210.                 data = JSON.parse(data);
  211.                 //устанавливаем элементу, содержащему текст ошибки, пустую строку
  212.                 $('#' + _this.idForm + '.error').text('');
  213.                 var submitForm = $('#' + _this.idForm);
  214.                 // если сервер вернул ответ success, то значит двнные отправлены
  215.                 if (data.result === "success") {
  216.                     $.jGrowl('Форма успешно отправлена!', {theme: 'jgrowl-success', life: 10000});
  217.                     document.getElementById(_this.idForm).reset();
  218.  
  219.                     submitForm.find('input,textarea').each(function () {
  220.                         _this.changeStateInput(this, 'clear');
  221.                     });
  222.                     if (_this.existenceUploadsFile) {
  223.                         $('#' + _this.idForm + ' .attachments').html(
  224.                             '<input type="file" name="attachment[]">' +
  225.                             '<p style="margin-top: 3px; margin-bottom: 3px; color: #ff0000;"></p>');
  226.                     }
  227.                     if (_this.existenceCaptcha) {
  228.                         _this.refreshCaptcha();
  229.                     }
  230.                     if (_this.hideForm) {
  231.                         submitForm.hide();
  232.                         submitForm.parent().find('.success-message').removeClass('hidden');
  233.                     }
  234.                 } else {
  235.                     _this.changeStateSubmit(false);
  236.                     $('#' + _this.idForm + ' .progress-bar').css('width', '0%');
  237.                     if (data.hasOwnProperty('captcha')) {
  238.                         var captcha = submitForm.find('[name="captcha"]').eq(0);
  239.                         $(captcha).val('');
  240.                         var imgCaptcha = submitForm.find('.img-captcha');
  241.                         var src = imgCaptcha.attr('data-src');
  242.                         if (src.indexOf('?id') !== -1) {
  243.                             src += '&rnd='+(new Date()).getTime();
  244.                         } else {
  245.                             src += '?rnd='+(new Date()).getTime();
  246.                         }
  247.                         imgCaptcha.attr('src',src);
  248.                     }
  249.  
  250.                     // если сервер вернул ответ error...
  251.                     $.jGrowl('<strong>Ошибка!</strong><br>Форму не удалось отправить.', {
  252.                         theme: 'jgrowl-warning',
  253.                         life: 10000
  254.                     });
  255.  
  256.                     // сбрасываем состояние всех input и textarea элементов
  257.                     submitForm.find('input,textarea').each(function () {
  258.                         _this.changeStateInput(this, 'clear');
  259.                     });
  260.  
  261.                     // отображаем все ошибки
  262.                     for (var error in data) {
  263.                         if (data.hasOwnProperty(error)) {
  264.                             if (error === 'result') { // кроме той, которая имеет ключ result
  265.                                 continue;
  266.                             }
  267.                             if (error !== 'info' && error !== 'log') { // кроме тех, которые имеют ключ info или log
  268.                                 $.jGrowl(data[error], {theme: 'jgrowl-error', life: 5000});
  269.                                 _this.changeStateInput($(submitForm).find('[name="' + error + '"]').eq(0), 'error');
  270.                             }
  271.                             if (error === 'info') { // выводим все сообщения с ключом info с помощью jGrowl
  272.                                 data[error].forEach(function (info, i, error) {
  273.                                     $.jGrowl(info, {theme: 'jgrowl-error', life: 5000});
  274.                                 });
  275.                             }
  276.                             if (error === 'log') { // выводим все сообщения с ключом log в консоль браузера
  277.                                 data[error].forEach(function (log, i, error) {
  278.                                     console.log(log);
  279.                                 });
  280.                             }
  281.                         }
  282.                     }
  283.                 }
  284.             },
  285.             error: function (request) {
  286.                 $.jGrowl('Произошла ошибка ' + request.responseText + ' при отправке данных.', {
  287.                     theme: 'jgrowl-error',
  288.                     life: 5000
  289.                 });
  290.             }
  291.         });
  292.     };
  293.  
  294.     // обновление капчи
  295.     ProcessForm.prototype.refreshCaptcha = function () {
  296.         var imgCaptcha = $('#' + this.idForm).find('.img-captcha');
  297.         var src = imgCaptcha.attr('data-src');
  298.         if (src.indexOf('?id') !== -1) {
  299.             src += '&rnd='+(new Date()).getTime();
  300.         } else {
  301.             src += '?rnd='+(new Date()).getTime();
  302.         }
  303.         imgCaptcha.attr('src',src);
  304.     };
  305.  
  306.     // изменение элемента input с type="file"
  307.     ProcessForm.prototype.changeInputFile = function (e) {
  308.         // условия для добавления нового элемента input с type="file"
  309.         var isSelectFile = e.currentTarget.files.length > 0;
  310.         var isNextInput = $(e.currentTarget).next('p').next('input[name="attachment[]"]').length === 0;
  311.         var isMaxInput = $('#' + this.idForm + ' input[name="attachment[]"]').length < this.countFiles;
  312.         var inputFile =
  313.             '<input type="file" name="attachment[]">' +
  314.             '<p style="margin-top: 3px; margin-bottom: 3px; color: #ff0000;"></p>';
  315.         if (isSelectFile && isNextInput && isMaxInput) {
  316.             $(e.currentTarget).next('p').after(inputFile);
  317.         }
  318.         // если файл выбран, то выполняем следующие действия...
  319.         if (e.currentTarget.files.length > 0) {
  320.             // получим файл
  321.             var file = e.currentTarget.files[0];
  322.             // проверим размер и расширение файла
  323.             if (file.size > this.maxSizeFile) {
  324.                 $(e.currentTarget).next('p').text('*Файл не будет отправлен, т.к. его размер больше ' + this.maxSizeFile / 1024 / 1024+ 'Мбайт');
  325.             } else if (!this.validateFileExtension(file.name)) {
  326.                 $(e.currentTarget).next('p').text('*Файл не будет отправлен, т.к. его тип не соответствует разрешённому');
  327.             } else {
  328.                 if ($(e.currentTarget).next('p')) {
  329.                     $(e.currentTarget).next('p').text('');
  330.                 }
  331.             }
  332.         } else {
  333.             // если после изменения файл не выбран, то сообщаем об этом пользователю
  334.             $(e.currentTarget).next('p').text('* Файл не будет отправлен, т.к. он не выбран');
  335.         }
  336.     };
  337.  
  338.     /*
  339.      Параметры указываются в виде:
  340.      {
  341.      ключ: значение;
  342.      ключ: значение;
  343.      ...
  344.      }
  345.      idForm - id формы обратной связи (по умолчанию feedbackForm)
  346.      existenceUploadsFile - наличие у формы блока загрузки файлов (по умолчанию true)
  347.      countFiles - количество файлов для загрузки (по умолчанию 5)
  348.      maxSizeFile - максиальный размер файла в байтах (по умолчанию 524288 байт)
  349.      validFileExtensions - допустимые расширения файлов (по умолчанию 'jpg','jpeg','bmp','gif','png')
  350.      existenceCaptcha - наличие у формы капчи (по умолчанию true)
  351.      hideForm - скрыть форму после отправки данных
  352.      disableAgreement - отключить проверку пользовательского соглашения (по умолчанию false)
  353.  
  354.      */
  355.     var formFeedback = new ProcessForm({idForm: 'feedbackForm', maxSizeFile: 5242880});
  356.     formFeedback.init();
  357.  
  358.     //var contactForm = new ProcessForm({ idForm: 'contactForm', existenceUploadsFile: false, existenceCaptcha: false });
  359.     //contactForm.init();
  360.  
  361. });
  362.  

Подскажите, пожалуйста, в чем может быть проблема.
2. Мелкий - 05 Сентября, 2018 - 10:15:15 - перейти к сообщению
fantast пишет:
            // проверяем расширение загруженного файла
            if (!in_array($fileExtension, $allowedExtensions)) {

Найдите определение $allowedExtensions
3. fantast - 05 Сентября, 2018 - 10:36:20 - перейти к сообщению
Мелкий пишет:
fantast пишет:
            // проверяем расширение загруженного файла
            if (!in_array($fileExtension, $allowedExtensions)) {

Найдите определение $allowedExtensions

Спасибо тебе друг! Улыбка
оказывается это определение было совсем в другом файле:
$allowedExtensions = array('gif', 'jpg', 'png');
добавил и все сработало Улыбка

 

Powered by ExBB FM 1.0 RC1