Template form html php

Генерация HTML-кода форм с помощью языка PHP

Построение формы с сохранением уже введённых значений — не такая уж простая задача, особенно если приходится иметь дело со списками значений для выбора или c полями, соответствующими массивам. Предлагаемые инструменты позволяют свести решение этой проблемы к описанию полей формы в виде простых конфигураций и подключению нужных HTML-шаблонов.

Состав пакета

В состав инструментария входят:

  • функция для генерации данных полей (код доступен в виде отдельного PHP-файла)
  • HTML-шаблоны полей (в виде архива)
  • обработчик шаблонов (ему посвящена отдельная статья, в которой и опубликован его код)

Основные принципы составления конфигурации полей

# 1. Получаем данные полей формы

require_once ‘make_form_data.php’ ; # Подключаем код функции

$cfg = array # Составляем конфигурацию полей
(
// первая группа
‘short_note’ ,
‘longer_text’ ,
‘some_file’ ,
‘flag’ ,

// вторая группа
‘period’ => array ( ‘values’ => array (
‘день’ ,
‘неделя’ ,
‘месяц’ ,
‘год’ ,
) ) ,
‘shape’ => array ( ‘values’ => array (
’round’ => ‘круглый’ ,
‘square’ => ‘квадратный’ ,
‘triangle’ => ‘треугольный’
) ) ,
‘size’ => array ( ‘values’ => array (
array ( ‘value’ => » , ‘title’ => ‘— размер —‘ ) ,
array ( ‘value’ => ‘small’ , ‘title’ => ‘маленький’ ) ,
array ( ‘value’ => ‘medium’ , ‘title’ => ‘средний’ ) ,
array ( ‘value’ => ‘big’ , ‘title’ => ‘большой’ ) ,
) ) ,
‘color’ => array ( ‘attr’ => array ( ‘size’ => 5 ) , // число видимых элементов
// у
‘values’ => array (
‘black’ ,
‘white’ ,
‘red’ => ‘красный’ ,
‘blue’ => ‘синий’ ,
array ( ‘value’ => ‘green’ , ‘title’ => ‘зеленый’ )
) ) ,
) ;

$FORMDATA = make_form_data ( $cfg , $_POST ) ; # Генерируем данные полей
# с учетом параметров HTTP-запроса
# 2. Получаем HTML-код формы

require_once ‘websun.php’ ; # Подключаем обработчик шаблонов

$HTML = websun_parse_template_path ( $FORMDATA , ‘form.tpl’ ) ; # Подставляем данные
# в HTML-шаблон формы

Составить конфигурацию для этих полей очень просто — надо всего лишь указать их имена 1 .

В шаблоне формы каждому из полей соответствует запись вида :

Список с возможностьюодновременного выборанескольких значений

Атрибуты полей

Случается, что полю нужно присвоить какой-то атрибут, будь то класс, стиль или текст-заглушка. Сделать это можно, включив в конфигурацию поля параметр attr , в котором нужные атрибуты следует перечислить в формате ‘имя’ => ‘значение’ 2 . Например, конфигурация

‘input_2’ => array (
‘attr’ => array (
‘placeholder’ => ‘пишите сюда’ ,
‘class’ => ‘special’ ,
‘style’ => ‘border: 2px solid #808080; padding: 2px’ ,
) ,
)

в сочетании с шаблоном input.tpl даст:

type = «text»
name = «input_2»
value = «»
placeholder= «пишите сюда» class = «special» style = «border: 2px solid #808080; padding: 2px»
>

Значения атрибутов перед вставкой обрабатываются функцией htmlspecialchars(). 3

Поля, соответствующие ассоциативным массивам

Форма может содержать поля для указания нескольких значений одного и того же свойства, которые в HTTP-запросе удобно получать в виде ассоциативного подмассива.

Например, ограничение по цене удобно иметь в виде

Получить соответствующий набор полей можно, указав в конфигурации параметр keys :

В массиве для подстановки в шаблон добавится уровень вложенности, и к полям нужно будет обращаться по ключам:

Бывает нужно дифференцировать отдельные поля, указав те или иные индивидуальные свойства. В этом случае элементы массива keys принимают формат описания конфигурации поля 4 . Например:

Читайте также:  Java create application exception

‘price’ => array (
‘keys’ => array (
‘min’ => array (
‘attr’ => array (
‘placeholder’ => ‘от’ ,
) ,
) ,
‘max’ => array (
‘attr’ => array (
‘placeholder’ => ‘до’ ,
) ,
) ,
) ,
) ;

Ключей может быть более двух: ‘keys’ => array ( ‘min’ , ‘max’ , ‘avg’ , . ) и т.д. 5

1. ▲ Сокращенной записи вида ‘имя’ соответствует полная форма ‘имя’ => array ( )

2. ▲ Атрибуты, которые обычно применяют без значений, указываются с дублированием:
‘readonly’ => ‘readonly’ , ‘disabled’ => ‘disabled’ и т.п.

3. ▲ Это удобно, в частности, когда в качестве атрибута нужно использовать JSON. Например:

4. ▲ При этом параметры, не указанные в элементе keys , наследуются от родительской конфигурации.

5. ▲ Вложенность ключей может быть многоуровневой:

© Все права на данную статью принадлежат порталу webew.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в печатных изданиях допускается только с разрешения редакции.

Источник

Create a Contact Form in PHP

Monty Shokeen

Monty Shokeen Last updated Apr 15, 2021

No matter what type of website you own or manage, you probably need a contact form. The contact form can help your visitors request a quote, ask for information, or share any tips or problems they’re facing while using your website.

In this tutorial, our focus will be on creating a fully functional contact form in PHP from beginning to end. We’ll begin with the markup of all the fields that we need to add and the basic styling of the contact form. After that, we’ll move on to the PHP code to implement its functionality.

Of course, the easiest way to create a contact form is to download a professional contact form script from CodeCanyon.

But if you want to learn about how a contact form is created, read on! It might just be easier than you think.

Markup of Our HTML Contact Form

The first step towards creating our own contact form is to code the markup. We’ll start doing that once we have a list of all the elements that we want inside our form. We’ll need an input field for the name of the person who is contacting us, and we’ll need a field for their email address so that we can reply to them if the need arises. We’ll also need an input field for the reason people are contacting you and a textarea where users can type their message.

If the website you’re managing is very popular, you’ll be getting a lot of emails through the contact form. To make sure that the right people get to read those emails and respond quickly, you need a couple more fields. For instance, you could add a field that can determine which department the visitor wants to contact, like marketing, support, or billing. This information can later be used to route the email appropriately. Ultimately, that might help you reply more quickly and sort the emails more efficiently.

How many fields you add to the contact form depends on the type of website you run, but make sure you don’t overdo it. Forcing visitors to fill out too many details might discourage them from contacting you altogether.

Читайте также:  List to string array python

Let’s write the HTML code to add all the fields I just mentioned into our contact form.

 action="contact.php" method="post"> 
 type="text" id="name" name="visitor_name" placeholder="John Doe" pattern=[A-Z\sa-z] required> 
 type="email" id="email" name="visitor_email" placeholder="john.doe@email.com" required> 
 for="department-selection">Choose Concerned Department 
 id="department-selection" name="concerned_department" required> 
 value="technical support">Technical Support 
 for="title">Reason For Contacting Us 
 type="text" id="title" name="email_title" required placeholder="Unable to Reset my Password" pattern=[A-Za-z0-9\s] > 
 for="message">Write your message 
 id="message" name="visitor_message" placeholder="Say whatever you want." required> 

Before proceeding any further, I’d like to quickly summarize the meaning of some important attributes in the above markup. The action attribute in the form determines where the form data needs to be sent. If you don’t have an action attribute, the data is sent back to the same URL. Here we’ve used contact.php, so the form data will be sent to that script.

The name attribute for different input elements in the form is used to access the element values on the server side. For example, in the above form, you can get the name of the visitor contacting you using $_POST[‘visitor_name’] in contact.php.

We use the placeholder attribute to give users a basic idea of the expected input for each field in the form. The required attribute ensures that no important field is left blank before the user hits the submit button on the form.

The pattern attribute is used to enforce some rules on the kinds of values that can go inside certain fields. In our case, we only allow users to use letters and the space character in the names they submit. We also limit the total number of acceptable characters to anything from 3 to 20 inclusive. The pattern that you use will depend on the type of input that you want from users.

The following CodePen demo shows us what our simple contact form PHP looks like with the above markup and a little bit of CSS.

Making Our HTML Contact Form Functional Using PHP

Right now, our PHP contact form doesn’t do anything useful. Visitors can fill it out and hit the send message button, but we won’t receive anything because there is no server-side code to handle the information provided by the form. In this section, we’ll make our custom contact form functional using PHP.

Begin by creating a contact.php file and putting the following code inside it.

$visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING); 
  ".$visitor_name."  
if(isset($_POST['visitor_email']))  
$visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']); 
$visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL); 
  ".$visitor_email."  
$email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING); 
  ".$email_title."  
if(isset($_POST['concerned_department']))  
$concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING); 
  ".$concerned_department."  
if(isset($_POST['visitor_message']))  
$visitor_message = htmlspecialchars($_POST['visitor_message']); 
if($concerned_department == "billing")  
$recipient = "billing@domain.com"; 
else if($concerned_department == "marketing")  
$recipient = "marketing@domain.com"; 
else if($concerned_department == "technical support")  
$recipient = "tech.support@domain.com"; 
$recipient = "contact@domain.com"; 
$headers = 'MIME-Version: 1.0' . "\r\n" 
.'Content-type: text/html; charset=utf-8' . "\r\n" 
if(mail($recipient, $email_title, $email_body, $headers))  
echo "

Thank you for contacting us, $visitor_name. You will get a reply within 24 hours.

"
;
echo '

We are sorry but the email did not go through.

'
;
echo '

Something went wrong

'
;

We have already done some client-side validation of user input. However, it’s always safer to do server-side validation as well. We use the filter_var() function to sanitize the name provided by the user. In a similar fashion, we also sanitize the value of $email_title and $concerned_department . You can use the filter_var() function to validate or sanitize all types of user input. We also use the htmlspecialchars() function to encode all the special HTML characters in the visitor message sent to us.

The value of $recipient is based on the value of the variable $concerned_department . This way, we make sure that only people who are actually supposed to look into the matter receive the email.

Also, we’ve used the $email_body variable to format the email body which will be the main content of the email. As we are sending an email in the HTML format, we’ve used HTML to format the email body content.

Finally, we use the mail() function to send an email which includes the information the visitor wanted us to know. Upon successful delivery of the email, we let the visitors know that we have received their email and that they’ll be contacted soon.

Security is paramount when you’re dealing with user data or input. Whether you should validate or sanitize the user input depends on what the input is and how you want to use it.

Validation simply checks if the user input follows a certain set of rules. For example, validation could check that the name of a person does not contain any numbers.

Sanitization is used to remove any offending characters that pose a security risk. For example, a malicious user trying to contact you through the form might add a script tag in the textarea to get you to download a harmful script. This is particularly worrisome when your website has public forums accessible by everyone.

However, you have to be very careful when getting rid of unwanted characters in user input. For example, you might decide to use filter_var($user_input, FILTER_SANITIZE_STRING); on some input to strip all tags and encode special characters. However, this flag also strips harmless character input by legitimate users. Here is an example:

Источник

Оцените статью