и
). Для этого применяется набор атрибутов formaction
, formmethod
, formenctype
и formtarget
, которые являются аналогами соответствующих атрибутов без приставки form. В примере 4 показано использование этих атрибутов.Пример 4. Отправка формы
HTML5
IE
Cr
Op
Sa
Fx
Отправка формы
Все новые атрибуты форм не поддерживаются некоторыми браузерами, в частности, Internet Explorer и Safari.
This is in continuation of the tutorial on making a membership based web site. Please see the previous page for more details.
Download the code You can download the whole source code for the registration/login system from the link below:
The ReadMe.txt file in the download contains detailed instructions.
The login form Here is the HTML code for the login form.
Logging in We verify the username and the password we received and then look up those in the database. Here is the code:
function Login()
{
if(empty($_POST["username"]))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST["password"]))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
if(!$this->CheckLoginInDB($username,$password))
{
return false;
}
session_start();
$_SESSION[$this->GetLoginSessionVar()] = $username;
return true;
}
In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable.
Here is the code to look up the username and password .
function CheckLoginInDB($username,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$username = $this->SanitizeForSQL($username);
$pwdmd5 = md5($password);
$qry = "Select name, email from $this->tablename ".
" where username="$username" and password="$pwdmd5" ".
" and confirmcode="y"";
$result = mysql_query($qry,$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error logging in. ".
"The username or password does not match");
return false;
}
return true;
}
Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set an “authorized” session variable, and then redirect to the protected content. If there are no rows with the entered data, we just redirect the user to the login form again.
Access controlled pages For those pages that can only be accessed by registered members, we need to put a check on the top of the page.
Notice that we are setting an “authorized” session variable in the login code above. On top of pages we want to protect, we check for that session variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.
Include this sample piece of code on top of your protected pages:
CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
See the file: access-controlled.php
in the downloaded code for an example.
Here is the CheckLogin() function code.
function CheckLogin()
{
session_start();
$sessionvar = $this->GetLoginSessionVar();
if(empty($_SESSION[$sessionvar]))
{
return false;
}
return true;
}
These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a “Forgot password” page to allow the user to retrieve or change his password if he forgets it.
Updates 9th Jan 2012
Reset Password/Change Password features are added.
The code is now shared at GitHub .
License
The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.
No related posts.
Comments on this entry are closed.
Login forms can be found in websites with forums, shops, WordPress and mostly everything on the internet requires login form somewhere to get access to something. The whole web is incomplete without login forms and registration, signups forms.
HTML forms will be first which most of us come across and with proper CSS which gives style to the HTML structure . In latest HTML versions i guess HTML seems to have opted for CSS3 as their default structure styling option. Anyways what you find here is the pre designed HTML, CSS forms built by front end developers and shared to the public for free to use.
Try to use all these free login form templates as most of them also have pre built HTML validation features as well as some opt jQuery or HTML validation (like the Login/Register form with pass meter below).
This list is not over yet, i am interested in finding new login form designs so i will keep updating these list with new login form templates when they show up in 2017. Stay tuned.
Red Login Form A simple and effective login form for your website which requires basic input fields and no extra programming.
A flat login form design designed for your website which is already flat. Download and use this template for any purpose.
Require a quick signin for your clients ? No worries, this pretty looking login form will get you going without any hassles. Download the source code and check the demo as you can put a sample username and password in the fields and try to login. You will be taken to a profile page on the same which looks glorious with a logout button which shows the logging out animation.
With google material design getting popular over flat design we can see a deep and carefully shadowed login form and a register form in this css3 template.
Here you get another brilliant login form for your busienss website with a option to hide/show login fields. Well coded css/html/js design will give you better loading without tampering your current site speed.
Minimal Login Form with fluid animation A smooth animation of login form which opens up the login section by clicking a picture or a button as you need.
Minimalistic Login Form with css Here you will find a no-fancy login form ui which is placed on a full screen background. The download file will get you css and html for easy implementation of this login to your website.
Animated Login Form The click animations displayed on text fields is brilliant which displays a small sliding animation of user and password icons. You can then login the form to watch a authenticating pre loader as well as a welcome back block. This download contains all the source files to implement a login form for your own website.
Elegant Login This is a simple version of login form you can display on your website as this also has less impact on site speed with its minimal code.
Calm Login Screen A clean login form with animated background giving a relaxing feel to the whole page. Download the whole template in zip format from codepen.
Login and Signup Form Integrate this fluid login and signup form on to your website with ease. The zip file with this download will provide you with css, html and js templates. Social media signup is also available with password show/hide options for on screen easy password entry.
Login Form with Create Account A login form which displays with a fadein effect is just amusing to watch. This effect can be seen only in few modern login forms. Use the click me to change the form to signup or create form.
Demo
| Download
A clean template with free html,css using minimal code and design for a website login page.
Download
A simple transparent form for login pages which is pure css and html.
Download
Unique Style for Login A login form which is totally unique with a character of interest.
Download
Classic HTML Login Form An example of old school login form with modern day styles with css3 only.
Download
Signin form A form with a cool border line and minimal css code and this is worth a try.
Download
New CSS3 Login Form A simple login form with only pure css3 as no jquery is used. For validation lite JavaScript is used in html form template.
Download
A minimal style login form with flat design can be download from the link below. HTML validation is available and set in this login template.
Download
Minimal Form Template for Login A validation for email is in palce and this tempalte is pure css, html with no fancy jquery modules.
Download
Signup/Login Form A single form to login to the website as well as a signup, register option which can be flipped with a click. Even though the signup area is missing some important fields this is nonetheless better form with all powerful features.
Download
This login form is hidden unles you click on login link. This is a very useful feature for modern day website which can avoid an extra page for login. Display login on any page you like with this powerful login form.
Download
It’s provided both as a PSD and as a fully-coded HTML/CSS version, so you can get started integrating it straight away.
Login Form (Coded) A professional login form. The download includes the PSD file, and I also felt like coding it so I included the xHTML, Js and CSS files as well.
Download
Как вы уже знаете, веб-клиент имеет возможность передавать веб-серверу различную информацию при помощи GET и POST-запросов. HTML-формы
- это основной инструмент для создания таких запросов. По сути, HTML-форма представляет собой поле или поля для ввода информации на веб-странице. Наглядным примером HTML-формы служит форма ввода логина и пароля для авторизации на сайте.
HTML-форма описывается с помощью парного тега form
. Этот тег имеет два важнейших атрибута: method
и action
. В атрибуте method задается тип HTTP-запроса (get или post), в action - запрашиваемый документ, то есть путь к файлу, запрос которого будет осуществлен. Путь может быть как абсолютным (с указанием домена сайта), так и относительным. Например:
<form
method
=
"get"
action
=
"/login.php"
>
...
</
form
>
Существует несколько различных видов элементов для ввода данных, которые помещаются внутри формы. Элемент, с которого я хотел бы начать, называется submit
:
<input
type
=
"submit"
value
=
"Войти"
/
>
Элемент представляет собой кнопку, нажатие на которой приводит к выполнению HTTP-запроса. Атрибут value
задает надпись на кнопке. Форма может содержать несколько элементов submit. Чтобы в запрашиваемом документе определить, по какой именно из кнопок было произведено нажатие, необходимо элементам submit установить атрибуты name
. Например:
<form
method
=
"get"
action
=
"/control.php"
>
<input
type
=
"submit"
name
=
"submit"
value
=
"Add"
/
>
<input
type
=
"submit"
name
=
"submit"
value
=
"Edit"
/
>
</
form
>
При формировании запроса веб-браузер включит HTTP-параметр, характеризующий нажатый элемент submit. В качестве имени параметра будет взято значение атрибута name нажатой кнопки, в качестве значения - значение атрибута value. Таким образом, при нажатии кнопки Add будет сформирован запрос:
/control.php?submit=Add
а при нажатии кнопки Edit:
/control.php?submit=Edit
Следующий элемент представляет собой простейший элемент для ввода однострокового текста. Его HTML-код:
<input
type
=
"text"
name
=
"name"
/
>
name - обязательный атрибут для участия в HTTP-запросе. Значение этого атрибута будет использовано в качестве имени HTTP-параметра. Этот атрибут имеется у всех типов элементов форм.
Элементу можно также задать атрибут value, указав в нем текст, который по-умолчанию будет введен в элементе. Например:
<input
type
=
"text"
name
=
"login"
value
=
"Имя пользователя"
/
>
Элемент password
служит для ввода паролей. Внешне он такой же, но введенный текст отображается в виде звездочек или точек:
<input
type
=
"password"
/
>
Этого, в принципе, достаточно для создания простейшей формы авторизации. Давайте попробуем ее реализовать, а затем вернемся к рассмотрению остальных типов элементов.
Создадим файл auth.php в корневом каталоге со следующим содержимым:
<html
xmlns=
"http://www.w3.org/1999/xhtml"
>
<head
>
<title
>
Авторизация</
title
>
<meta
http-equiv
=
"Content-Type"
content
=
"text/html;charset=utf-8"
/
>
</
head
>
<body
>
<form
method
=
"get"
action
=
"/auth.php"
>
<table
>
<tr
>
<td
>
Имя пользователя:</
td
>
<td
>
<input
type
=
"text"
name
=
"login"
value
=
""
/
>
</
td
>
</
tr
>
<tr
>
<td
>
Пароль:</
td
>
<td
>
<input
type
=
"password"
name
=
"pass"
value
=
""
/
>
</
td
>
</
tr
>
</
table
>
<input
type
=
"submit"
value
=
"Войти"
/
>
</
form
>
</
body
>
</
html
>
Как видите, внутри тега form можно размещать теги, помогающие красиво разметить форму (я внутрь поместил таблицу). Форма содержит поля для ввода имени пользователя и пароля с именами login и pass соответственно. При нажатии "Войти" формируется GET-запрос документа /auth.php (то есть, страница запрашивает саму себя). В моем случае полный URL страницы имел вид http://test-domain3/auth.php
.
Введите данные и нажмите "Войти". Страница должна перезагрузиться. Должен также измениться и адрес страницы. В моем случае он принял вид:
Http://test-domain3/auth.php?login=Joker-jar&pass=12345
Это означает, что документ auth.php был запрошен с GET-параметрами, которые были введены с помощью HTML-формы. Поместите в начало файла auth.php PHP-обработчик, который будет принимать данные для авторизации:
//--Проверяем, были ли переданы данные
if
( isset
($_GET
[
"login"
]
)
&&
isset
($_GET
[
"pass"
]
)
)
{
echo
"Ваше имя пользователя: "
.
$_GET
[
"login"
]
.
", ваш пароль: "
.
$_GET
[
"pass"
]
;
exit
;
}
?>
Если странице были переданы логин и пароль, условие сработает и сообщение будет выведено. Также будет вызван exit
, который прекратит дальнейшее выполнение скрипта, следовательно форма выведена не будет.
Передавать пароль с помощью GET-запроса небезопасно, так как он виден в адресной строке. Сменим тип запроса на POST. Для этого изменим значение атрибута method, а в PHP-обработчике обращения к массиву $_GET изменим на $_POST. Проверьте работоспособность скрипта.
Следующий элемент - флажок
. Его применяют, когда от пользователя необходим ответ вида "да/нет":
<input
type
=
"checkbox"
/
>
Если флажок не отмечен, в параметрах ничего не передается. Иначе передается параметр name со значением on
. Есть еще один момент. Как правило, рядом с флажком присутствует поясняющая надпись. Хорошим тоном является реализация веб-мастером реакции флажка на клики по этой надписи. Делается это просто. Флажку присваивается определенный id, а сама надпись оформляется тегом label
с атрибутом for
, значение которого равно идентификатору флажка:
<input
type
=
"checkbox"
id
=
"remember"
name
=
"remember"
/
>
<label
for
=
"remember"
>
Запомнить меня</
label
>
Похожий элемент используется для выбора ответа из набора значений. Допустим, пользователю необходимо выбрать один из трех цветов:
<input
type
=
"radio"
id
=
"red"
name
=
"color"
value
=
"red"
/
>
<label
for
=
"red"
>
Красный</
label
>
<br
/
>
<input
type
=
"radio"
id
=
"green"
name
=
"color"
value
=
"green"
/
>
<label
for
=
"green"
>
Зеленый</
label
>
<br
/
>
<input
type
=
"radio"
id
=
"blue"
name
=
"color"
value
=
"blue"
/
>
<label
for
=
"blue"
>
Синий</
label
>
<br
/
>
Обратите внимание, что у всех элементов одинаковое значение name . Можно выбрать только одно значение. В HTTP-параметра передастся value выбранного элемента, например color=blue
.
Чтобы изначально был выбран какой-то из элементов, например, первый, ему нужно задать атрибут checked
со значением checked
(стандарт XHTML):
<input
type
=
"radio"
id
=
"red"
name
=
"color"
value
=
"red"
checked
=
"checked"
/
>
Для ввода большого многострочного текста существует специальный элемент textarea
:
<textarea
rows
=
"6"
cols
=
"20"
name
=
"text"
>
Текст внутри элемента</
textarea
>
Текст внутри элемента
Этот элемент, как видите, отличается от предыдущих. Он представляет собой парный тег, а текст помещается не в атрибут, а в тело тега. У элемента также есть атрибут name. При помощи атрибута rows
можно задать количество строк в элементе, cols
- количество символов в строке. Элемент textarea используется, как правило, в POST-формах, т.к. предполагает ввод длинного текста (например, форма сообщения на форуме).
Выпадающий список. Наверняка сталкивались с таким элементом в программах. Позволяет выбрать одно значение из набора. Код элемента также не совсем обычен. Сначала создается элемент-контейнер select
, ему задается атрибут name:
<select
name
=
"towns"
>
</
select
>
Внутрь контейнера помещаются элементы списка. Элемент списка представляет собой парный тег option
, каждому элементу задается атрибут value. В тело элемента прописывается надпись элемента:
<select
name
=
"town"
>
<option
value
=
"msk"
>
Москва</
option
>
<option
value
=
"vlad"
>
Владивосток</
option
>
<option
value
=
"nsk"
>
Новосибирск</
option
>
</
select
>
В HTTP-запросе передается параметр с именем name и значением value выбранного элемента, например town=vlad
. По умолчанию выбран первый элемент списка, если хотите, чтобы был выбран другой элемент, задайте ему атрибут selected
со значением selected
:
<option
value
=
"vlad"
selected
=
"selected"
>
Владивосток</
option
>
Список значений. Если элементу select задать атрибут size
с числовым значением, выпадающий список превратится в список значений. При этом значение атрибута size будет определять вертикальный размер элемента:
<select
name
=
"town"
size
=
"3"
>
<option
value
=
"msk"
>
Москва</
option
>
<option
value
=
"vlad"
>
Владивосток</
option
>
<option
value
=
"nsk"
>
Новосибирск</
option
>
</
select
>
Москва Владивосток Новосибирск
Если элементу select задать атрибут multiple
со значением multiple
(стандарт XHTML), то появится возможность выбирать более одного элемента одновременно (например, с зажатой клавишей Ctrl ). В этом случае в HTTP-запросе будут переданы все выбранные элементы с одинаковыми именами, например: town=msk&town=vlad&town=nsk
.
Иногда необходимо в HTTP-запросе передать параметр, который пользователь не должен редактировать, а порой даже и видеть. Допустим, вы реализуете форму редактирования новости. В HTTP-запросе необходимо передавать идентификатор этой новости. Для подобных случаев есть скрытый элемент HTML-форм:
<input
type
=
"hidden"
name
=
"param"
value
=
""
/
>
Этот элемент не будет виден на форме, но при выполнении запроса будет передан HTTP-параметр name=value.
Иногда может пригодиться элемент, очищающий форму. Кнопка, при нажатии на которую все введенные пользователем данные на форме стираются:
<input
type
=
"reset"
value
=
"Очистить"
/
>
Перечисленные элементы имеют два специальных атрибута:
readonly="readonly" - запрещает изменение информации в элементе (режим "только для чтения); disabled="disabled" - делает элемент неактивным.
Существует также элемент для выбора файла, который при сабмите формы будет загружен на веб-сервер, но об этом, пожалуй, в отдельной статье.