Wi-Fi        02.03.2024   

Отправка данных формы. Форма входа и регистрации с помощью HTML5 и CSS3 Безысходный login form register html

Всем привет. Итак, мы изучили несколько элементов для создания форм. Пришло время объединить наши знания для решения задачи побольше. Давайте создадим самую простую форму для авторизации на сайте. Для этого нам необходимы два поля, делаем и привязываем к ним подписи.

Первое поле – для логина, второе – для пароля. И вот со вторым не все так просто. Поскольку на текущий момент оно представляет собой просто поле для ввода текста.

Результат в браузере:

Чтобы введенный в нем текст заменялся на звездочки, как это принято для поля такого типа, необходимо сделать одно простое действие. А именно, осуществить замену значения атрибута type на password :

Результат:

Кнопка отправки формы

Ну, вот. Наша форма уже почти готова. Теперь, чтобы завершить ее создание, необходимо сделать кнопку, которой будет осуществляться отправка формы. Задача решается с применением тега с типом submit .

Если на кнопке должна присутствовать какая-то надпись, то ее можно сделать, используя атрибут value . Задавать имя кнопке или нет – на ваше усмотрение, но если вы это сделаете, то сервер будет получать это имя, а также значение кнопки.

Как правило, в имени кнопки отправки формы есть потребность тогда, когда у формы есть несколько кнопок, каждая из которых выполняет определенное действие. Благодаря этому сервер, получая от браузера имя и значение кнопки, понимает, на какую именно кнопку нажал пользователь и что, соответственно, необходимо выполнить.

В итоге код нашей формы получится следующим:

Результат в браузере:

В этом уроке будем создавать форму регистрации в четыре шага: 1. Ввод Логина и Пароля 2. Имя Фамилия и Адрес электронной почты 3. Возраст, Пол и Страна 4. Общая информация

HTML

В начале, как обычно, создадим разметку html . Нам нужен контейнер с четырьмя блоками DIV , по одному на каждый шаг.
Основной код html будет таким:

Внутрь каждого блока мы поместим поля и простые label :

Зарегистрируйтесь на сайт

Мы использовали три поля ввода: Логин, Пароль и Подтвержение пароля , а в конце блока тег input с типом submit для перехода на следующий шаг. Другие блоки работают точно также.
В конце контейнера у нас простой индикатор выполнения, вот его код:

0% Выполнено

Полный html код такой:

Зарегистрируйтесь на сайт

Зарегистрируйтесь на сайт

Зарегистрируйтесь на сайт

Зарегистрируйтесь на сайт

Общая информация

Логин
Пароль
Email
Имя
Возраст
Пол
Страна
0% Выполнено

Как вы могли заметить, на четвертом шаге таблица пустая. Мы заполним её информацией, вводимой пользователем с помощью jQuery.

CSS

Теперь добавим стили к форме. Будем применять правило @fontface для использования пользовательских шрифтов. В нашем случае это шрифт Cantarell . Полный код CSS приведен ниже:

/* CSS Reset (Eric Meyer) */ html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent;margin:0;padding:0}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}:focus{outline:0}ins{text-decoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0} @font-face { font-family: "Cantarell"; src: url(../fonts/Cantarell-Regular.eot); src: local("Cantarell"), url("../fonts/Cantarell-Regular.ttf") format("truetype"); } body { background-color: #f9f9f9; color: #222; font-family: Cantarell, Verdana, sans-serif; font-size: 12px; } input::-moz-focus-inner, input::-moz-focus-inner { border: none; } input:focus, input:focus { outline: none; } .clear { clear: both; } #container { background: url("../images/container.png") no-repeat; width: 754px; height: 370px; margin: 20px auto; padding: 50px 0; overflow: hidden; position: relative; } #container #first_step, #second_step, #third_step, #fourth_step { display: none; } #container #first_step { display: block; } #container .form { margin: 66px 72px 0 72px; } #container h1, #container h2 { font-size: Cantarell, Verdana, sans-serif; text-align: center; font-size: 24px; text-shadow: 1px 1px 2px #222; } #container h1 span { color: #a90329; } #container h2 { color: #888; font-size: 20px; text-align: left; text-shadow: none; } #container table { margin: 20px 40px; font-size: 14px; font-weight: bold; } #container table td { padding: 5px 10px; } #container table td:nth-child(2) { color: #a90329; } #container input, #container select { background: url("../images/input.png") no-repeat; color: #888; border: 1px solid #ccc; font-family: Cantarell, Verdana, sans-serif; font-weight: bold; font-size: 15px; width: 300px; height: 35px; padding: 0 25px; margin: 20px 0; float: left; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } #container input.submit { background: url("../images/button.png") no-repeat; border: none; cursor: pointer; width: 85px; height: 38px; position: relative; bottom: 2px; left: 655px; } #container input.submit:focus { border: none; } #container input.send{ background: url("../images/send.png") no-repeat; } #container input.error { border: 1px solid red; } #container input.valid { border: 1px solid #1FFF00; } #container input:focus, #container select:focus { border: 1px solid #a90329; color: #a90329; } #container select { padding: 5px 0 5px 25px; } #container option { padding: 0 15px; } #container label { color: #666; font-size: 12px; font-weight: bold; line-height: 14px; float: right; margin: 23px -25px; width: 270px; } #progress_bar { background: url("../images/progress_bar.png") no-repeat; width: 339px; height: 24px; margin: 0 auto; position: relative; } #progress { background: url("../images/progress.png") repeat-x; width: 0px; height: 23px; border-radius: 20px; -webkit-border-radius: 20px; -moz-border-radius: 20px; } #progress_text { position: relative; line-height: 21px; text-align: center; font-weight: bold; color: white; text-shadow: 1px 1px 2px #222; width: 339px; height: 24px; top: -23px; left: 0; }

JS

jQuery будем использовать для плавной смены блоков (слайды), проверки правильности данных, изменения процента выполнения.
Нам нужно будет в шапке старницы подключить библиотеку jQuery и ещё два плагина:
jQuery UI и jQuery inputfocus (используется для управления фокусом и размытия событий формы).
jQuery код приведен ниже:

$(function(){ //original field values var field_values = { //id: value "username" : "Логин", "password" : "Пароль", "cpassword" : "Пароль", "firstname" : "Имя", "lastname" : "Фамилия", "email" : "email" }; //inputfocus $("input#username").inputfocus({ value: field_values["username"] }); $("input#password").inputfocus({ value: field_values["password"] }); $("input#cpassword").inputfocus({ value: field_values["cpassword"] }); $("input#lastname").inputfocus({ value: field_values["lastname"] }); $("input#firstname").inputfocus({ value: field_values["firstname"] }); $("input#email").inputfocus({ value: field_values["email"] }); //reset progress bar $("#progress").css("width","0"); $("#progress_text").html("0% Выполнено"); //first_step $("form").submit(function(){ return false; }); $("#submit_first").click(function(){ //remove classes $("#first_step input").removeClass("error").removeClass("valid"); //ckeck if inputs aren"t empty var fields = $("#first_step input, #first_step input"); var error = 0; fields.each(function(){ var value = $(this).val(); if(value.length<4 || value==field_values[$(this).attr("id")]) { $(this).addClass("error"); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass("valid"); } }); if(!error) { if($("#password").val() != $("#cpassword").val()) { $("#first_step input").each(function(){ $(this).removeClass("valid").addClass("error"); $(this).effect("shake", { times:3 }, 50); }); return false; } else { //update progress bar $("#progress_text").html("33% Выполнено"); $("#progress").css("width","113px"); //slide steps $("#first_step").slideUp(); $("#second_step").slideDown(); } } else return false; }); $("#submit_second").click(function(){ //remove classes $("#second_step input").removeClass("error").removeClass("valid"); var emailPattern = /^+@+\.{2,4}$/; var fields = $("#second_step input"); var error = 0; fields.each(function(){ var value = $(this).val(); if(value.length<1 || value==field_values[$(this).attr("id")] || ($(this).attr("id")=="email" && !emailPattern.test(value))) { $(this).addClass("error"); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass("valid"); } }); if(!error) { //update progress bar $("#progress_text").html("66% Выполнено"); $("#progress").css("width","226px"); //slide steps $("#second_step").slideUp(); $("#third_step").slideDown(); } else return false; }); $("#submit_third").click(function(){ //update progress bar $("#progress_text").html("100% Выполнено"); $("#progress").css("width","339px"); //prepare the fourth step var fields = new Array($("#username").val(), $("#password").val(), $("#email").val(), $("#firstname").val() + " " + $("#lastname").val(), $("#age").val(), $("#gender").val(), $("#country").val()); var tr = $("#fourth_step tr"); tr.each(function(){ //alert(fields[$(this).index()]) $(this).children("td:nth-child(2)").html(fields[$(this).index()]); }); //slide steps $("#third_step").slideUp(); $("#fourth_step").slideDown(); }); $("#submit_fourth").click(function(){ //send information to server alert("Данные отправлены"); }); });
Вот у нас и получилась форма с регистрацией в несколько шагов. Для использования данного примера нужно только изменить форму action с ссылкой на ваш php файл, используемый для хранения данных и отредактировать 132 строчку на:
$(‘form’).unbind(‘submit’).submit(); . Чтобы посмотреть форму в действии нажмите на кнопку Демо .

A tutorial on how to create a switching login and registration form with HTML5 and CSS3.

In this tutorial we are going to create two HTML5 forms that will switch between login and registration using the CSS3 pseudo class :target . We will style it using CSS3 and an icon font. The idea behind this demo is to show the user the login form and provide a link to “switch” to the registration form.

Note that this is for demo purpose only, it will only work in browser supporting the:target pseudo class, and you should not use this code on a live website without providing solid fallback.

In the following, we will be going through Demo 1.

The HTML

In the HTML, we will put both forms, hiding the second one with CSS. Here is the code, I’ll explain some of the interesting parts later.

Log in

Sign up

We’ve added some HTML5 goodness here and used some of the new inputs. The input type=password automatically hides what the user is typing and replaces it with dots (depending on browser). The input type=email enables the browser to check if what the user entered has the format of a valid email address. We’ve also used the require=required attribute; browsers that support this attribute will not let the user submit the form until this field is filled, no JavaScript required.
The autocomplete=on attribute will prefill values based on earlier user input. We also used some nice placeholders for the inputs that will show some guiding value when the input is not filled.

Now the two tricky parts. You might have noticed the two links at the top of the form. This is a little trick that will make our form behave nicely when playing with anchors, so that it won’t “jump” on long pages when we click on the switching link and trigger the:target pseudo-class.

The second little trick is related to the use of the icon font. We will be using a data-attribute to display the icons. By setting data-icon=”icon_character” with the according character in the HTML we will just need one CSS attribute selector to style all the icons. Read more about this technique on 24 Ways: Displaying Icons with Fonts and Data- Attributes .

The CSS

For the clearness of the code in this tutorial, I will omit all the vendor prefixes, but you will, of course, find them in the files. Once again, I’m using some pretty advanced CSS3 tricks that might not work in all browsers. Let’s get started.

Styling both forms using CSS3

First, let’s give our two forms some general styling for the container.

#subscribe, #login{ position: absolute; top: 0px; width: 88%; padding: 18px 6% 60px 6%; margin: 0 0 35px 0; background: rgb(247, 247, 247); border: 1px solid rgba(147, 184, 189,0.8); box-shadow: 0pt 2px 5px rgba(105, 108, 109, 0.7), 0px 0px 8px 5px rgba(208, 223, 226, 0.4) inset; border-radius: 5px; } #login{ z-index: 22; }

We’ve added a nice box shadow that’s made of two shadows: an inset one to create the inner blue glow, and an outside shadow. We’ll explain the z-index in a bit.

In the following we will style the header with some background clipping:

/**** general text styling ****/ #wrapper h1{ font-size: 48px; color: rgb(6, 106, 117); padding: 2px 0 10px 0; font-family: "FranchiseRegular","Arial Narrow",Arial,sans-serif; font-weight: bold; text-align: center; padding-bottom: 30px; } /** For the moment only webkit supports the background-clip:text; */ #wrapper h1{ background: -webkit-repeating-linear-gradient(-45deg, rgb(18, 83, 93) , rgb(18, 83, 93) 20px, rgb(64, 111, 118) 20px, rgb(64, 111, 118) 40px, rgb(18, 83, 93) 40px); -webkit-text-fill-color: transparent; -webkit-background-clip: text; } #wrapper h1:after{ content:" "; display:block; width:100%; height:2px; margin-top:10px; background: linear-gradient(left, rgba(147,184,189,0) 0%, rgba(147,184,189,0.8) 20%, rgba(147,184,189,1) 53%, rgba(147,184,189,0.8) 79%, rgba(147,184,189,0) 100%); }

Note that at this moment only webkit browsers support background-clip: text , so we will create a stripped background only for webkit here, and clip it to the text to add the stripes to the H1 title. Since the background-clip: text property currently only works in Webkit browsers, I decided to go only with the webkit prefix. That’s the reason why I split the CSS declaration into two parts, and use a webkit prefixed gradient only. Only using the –webkit- prefix is bad practice, it’s only for demo purpose, and you should never do this on real a website! That’s also where the -webkit-text-fill-color: transparent comes in handy: it enables us to only have a transparent background on the webkit browsers, all the other ones will ignore it and give us the provided text color fallback.

We also created a fading line under the title with the help of the:after pseudo-class. We use a 2px height gradient and fade the background to 0 opacity at both ends.

Now let’s style our inputs and give them a nicer look.

/**** advanced input styling ****/ /* placeholder */ ::-webkit-input-placeholder { color: rgb(190, 188, 188); font-style: italic; } input:-moz-placeholder, textarea:-moz-placeholder{ color: rgb(190, 188, 188); font-style: italic; } input { outline: none; }

First we style the inputs, and remove the outline. But be careful here; the outline helps the user know which input is focused, so if you remove it, you should provide some:active and:focus states for the inputs.

/* all the input except submit and checkbox */ #wrapper input:not(){ width: 92%; margin-top: 4px; padding: 10px 5px 10px 32px; border: 1px solid rgb(178, 178, 178); box-sizing: content-box; border-radius: 3px; box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.6) inset; transition: all 0.2s linear; } #wrapper input:not():active, #wrapper input:not():focus{ border: 1px solid rgba(91, 90, 90, 0.7); background: rgba(238, 236, 240, 0.2); box-shadow: 0px 1px 4px 0px rgba(168, 168, 168, 0.9) inset; }

Here we used the:not pseudo class, to style all inputs, except the checkbox. I provided a:focus and:active state, since I decided to remove the outline.

And now the fun part: the icon font. Since we can’t use:before and:after pseudo classes on inputs, we’ll have to cheat a little bit: we’ll add the icon to the label, and then place it in the input. I’m using the fontomas library which puts together some nice icons. You can rearrange them to set the icon to a specific letter. Remember the data-icon attribute? It’s where you should put the letter. I used data-icon=’u’ for user, ‘e’ for email, ‘p’ for password. Once I chose the letters, I downloaded the font, and used the fontsquirrel font generator to transform it into a @font-face compatible format.

@font-face { font-family: "FontomasCustomRegular"; src: url("fonts/fontomas-webfont.eot"); src: url("fonts/fontomas-webfont.eot?#iefix") format("embedded-opentype"), url("fonts/fontomas-webfont.woff") format("woff"), url("fonts/fontomas-webfont.ttf") format("truetype"), url("fonts/fontomas-webfont.svg#FontomasCustomRegular") format("svg"); font-weight: normal; font-style: normal; } /** the magic icon trick ! **/ :after { content: attr(data-icon); font-family: "FontomasCustomRegular"; color: rgb(106, 159, 171); position: absolute; left: 10px; top: 35px; width: 30px; }

Yeah, that’s it folks, you don’t need to have a class for each icon. We used content: attr(data-icon) to retrieve the letter from the data-icon attribute, so we only have to declare the font, choose a nice color and position it.

Now let’s style the submit button for both forms.

/*styling both submit buttons */ #wrapper p.button input{ width: 30%; cursor: pointer; background: rgb(61, 157, 179); padding: 8px 5px; font-family: "BebasNeueRegular","Arial Narrow",Arial,sans-serif; color: #fff; font-size: 24px; border: 1px solid rgb(28, 108, 122); margin-bottom: 10px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); border-radius: 3px; box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.07) inset, 0px 0px 0px 3px rgb(254, 254, 254), 0px 5px 3px 3px rgb(210, 210, 210); transition: all 0.2s linear; } #wrapper p.button input:hover{ background: rgb(74, 179, 198); } #wrapper p.button input:active, #wrapper p.button input:focus{ background: rgb(40, 137, 154); position: relative; top: 1px; border: 1px solid rgb(12, 76, 87); box-shadow: 0px 1px 6px 4px rgba(0, 0, 0, 0.2) inset; } p.login.button, p.signin.button{ text-align: right; margin: 5px 0; }

The trick here is to use the box-shadow in order to create some extra borders. You can only use one border, but as many box-shadows as you want. We will use the length value to create a “fake” second white border, 3px wide, with no blur.

Then we’ll style the checkbox, nothing very special here:

/* styling the checkbox "keep me logged in"*/ .keeplogin{ margin-top: -5px; } .keeplogin input, .keeplogin label{ display: inline-block; font-size: 12px; font-style: italic; } .keeplogin input#loginkeeping{ margin-right: 5px; } .keeplogin label{ width: 80%; }

We will style the bottom of the form using repeating linear gradients to create a striped background.

P.change_link{ position: absolute; color: rgb(127, 124, 124); left: 0px; height: 20px; width: 440px; padding: 17px 30px 20px 30px; font-size: 16px ; text-align: right; border-top: 1px solid rgb(219, 229, 232); border-radius: 0 0 5px 5px; background: rgb(225, 234, 235); background: repeating-linear-gradient(-45deg, rgb(247, 247, 247) , rgb(247, 247, 247) 15px, rgb(225, 234, 235) 15px, rgb(225, 234, 235) 30px, rgb(247, 247, 247) 30px); } #wrapper p.change_link a { display: inline-block; font-weight: bold; background: rgb(247, 248, 241); padding: 2px 6px; color: rgb(29, 162, 193); margin-left: 10px; text-decoration: none; border-radius: 4px; border: 1px solid rgb(203, 213, 214); transition: all 0.4s linear; } #wrapper p.change_link a:hover { color: rgb(57, 191, 215); background: rgb(247, 247, 247); border: 1px solid rgb(74, 179, 198); } #wrapper p.change_link a:active{ position: relative; top: 1px; }

Now you’ll notice that we’ve got two nice forms, but we really want only one to show at a time. So now is time for some animations!!

Creating the switching animation

The first thing to do is to hide the second form by setting the opacity to 0:

#register{ z-index: 21; opacity: 0; }

Remember that our login form had a z-index of 22? We will give the second form a z-index of 21, to put it “under” the login form.

And now the really good part: switching the forms using the:target pseudo class. What you really have to understand about:target, is that we will use anchors to make the transition. The normal behavior of an anchor link, is to jump to the target in the page. But we don’t want to jump anywhere, we only want to switch the forms. And here comes our trick using the two links at the top of the page. Instead of directly linking to the second form, and risking getting a “jumping” effect, we actually put the two links at the top of the page and give them display: none . This will avoid any page jump. Credit where credit’s due: I found this trick on CSS3 create (in French).

#toregister:target ~ #wrapper #register, #tologin:target ~ #wrapper #login{ z-index: 22; animation-name: fadeInLeft; animation-delay: .1s; }

So this is what happens: when we click on the Join us button, we trigger the #toregister. We then do the animation, by using the sibling selector ~ to find our #register element. We use an animation called fadeInLeft . Since we “hide” the form using zero opacity, we will use an animation that fades in, to make it appear. We’ve also changed the z-index, to make it appear on top of the other form.
The same happens for the other form.

And here is the code for the animation. We are using the CSS3 animation framework from Dan Eden and adapted it for this tutorial.

Animate{ animation-duration: 0.5s; animation-timing-function: ease; animation-fill-mode: both; } @keyframes fadeInLeft { 0% { opacity: 0; transform: translateX(-20px); } 100% { opacity: 1; transform: translateX(0); } }

The form that is “disappearing” will have another animation which will make it fade out to the left:

#toregister:target ~ #wrapper #login, #tologin:target ~ #wrapper #register{ animation-name: fadeOutLeftBig; } @keyframes fadeOutLeft { 0% { opacity: 1; transform: translateX(0); } 100% { opacity: 0; transform: translateX(-20px); } }

You can now use other animations from Dan Eden’s animate.css: just adjust your .animate class and replace the animation names. You will also find some custom animations at the end of the animate-custom.css file.

Well, that’s it folks. I hope you enjoyed the tutorial!

Please note, that in some browsers background-clip: text is not supported. In Internet Explorer 9 the transitions and animations don’t work, so there will be no fancy form switching. In Internet Explorer 8 and below the:target pseudo-class is not supported, so it won’t work at all (you’ll just see the login form).

В этой статье вы узнаете, как создать форму регистрации и авторизации , используя HTML, JavaScript, PHP и MySql. Такие формы используются почти на каждом сайте, в независимости от его типа. Они создаются и для форума, и для интернета магазина и для социальных сетей (такие как например Facebook, Twiter, Odnoklassniki) и для многих других типов сайтов.

Если у Вас сайт на локальном компьютере, то я надеюсь, что у Вас уже . Без него ничего работать не будет.

Создание таблицы в Базе Данных

Для того чтобы реализовать регистрацию пользователей, в первую очередь нам нужна База Данных. Если она у Вас уже есть, то замечательно, иначе, Вам нужно её создавать. В статье , я подробно объясняю, как сделать это.

И так, у нас есть База Данных (сокращённо БД), теперь нам нужно создать таблицу users в которой будем добавлять наших зарегистрированных пользователей.

Как создавать таблицу в БД, я также объяснил в статье . Перед тем как создать таблицу, нам необходимо определить какие поля она будет содержать. Эти поля будут соответствовать полям из формы регистрации.

Значит, подумали, представили какие поля будут у нашей формы и создаём таблицу users с такими полями:

  • id - Идентификатор. Поле id должно быть у каждой таблицы из БД.
  • first_name - Для сохранений имени.
  • last_name - Для сохранений фамилии.
  • email - Для сохранений почтового адреса. E-mail мы будем использовать в качестве логина, поэтому это поле должна быть уникальной, то есть иметь индекс UNIQUE.
  • email_status - Поле для указания, подтверждена ли почта или нет. Если почта подтверждена, то оно будет иметь значение 1, иначе значение 0.
  • password - Для сохранений пароля.


Если Вы хотите чтобы Ваша форма регистрации имела ещё какие-то поля, то Вы можете их здесь также добавить.

Всё, наша таблица users готова. Переходим к следующему этапу.

Подключение к Базе Данных

Базу данных мы создали, теперь необходимо к ней подключиться. Подключение будем осуществлять с помощью PHP расширения MySQLi.

В папке нашего сайта, создаём файл с именем dbconnect.php , и в нём пишем следующий скрипт:

Ошибка подключения к БД. Описание ошибки: ".mysqli_connect_error()."

"; exit(); } // Устанавливаем кодировку подключения $mysqli->set_charset("utf8"); //Для удобства, добавим здесь переменную, которая будет содержать название нашего сайта $address_site = "http://testsite.local"; ?>

Этот файл dbconnect.php нужно будет подключить к обработчикам форм.

Обратите внимание на переменную $address_site , здесь я указал название моего тестового сайта, над которым буду работать. Вы соответственно, укажите название Вашего сайта.

Структура сайта

Теперь давайте разберёмся с HTML структурой нашего сайта.

Шапку и подвал сайта вынесем в отдельные файлы, header.php и footer.php . Их будем подключать на всех страницах. А именно на главной (файл index.php ), на страницу с формой регистрации (файл form_register.php ) и на страницу с формой авторизации (файл form_auth.php ).

Блок с нашими ссылками, регистрация и авторизация , добавим в шапку сайта, чтобы они отображались на всех страницах. Одна ссылка будет ввести на страницу с формой регистрации (файл form_register.php ) а другая на страницу с формой авторизации (файл form_auth.php ).

Содержимое файла header.php:

Название нашего сайта

В итоге, главная страница, у нас выглядит так:


Конечно, у Вас на сайте может быть совсем другая структура, но это для нас сейчас не важно. Главное, чтобы присутствовали ссылки (кнопки) регистрации и авторизации.

Теперь перейдём к форме регистрации. Как Вы уже поняли, она у нас находится в файле form_register.php .

Идём в Базу Данных (в phpMyAdmin), открываем структуру таблицы users и смотрим какие поля нам нужны. Значит, нам нужны поля для ввода имени и фамилии, поле для ввода почтового адреса(Email) и поле для ввода пароля. И ещё в целях безопасности добавим поле для ввода капчи.

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

Перед выводом формы добавляем блок для вывода сообщений об ошибках из сессии.

И ещё момент, если пользователь уже авторизован, и он ради интереса заходит на страницу регистрации напрямую, написав в адресную строку браузера адрес_сайта/form_register.php , то мы в этом случае вместо формы регистрации, выведем ему заголовок о том, что он уже зарегистрирован.

В общем, код файла form_register.php у нас получился таким:

Вы уже зарегистрированы

В браузере, страница с формой регистрации выглядит так:


С помощью атрибута required , мы сделали все поля обязательными к заполнению.

Обратите внимание на код формы регистрации где выводится капча :


Мы в значение атрибута src для изображения, указали путь к файлу captcha.php , который генерирует данную капчу.

Посмотрим на код файла captcha.php :

Код хорошо закомментирован, поэтому я остановлюсь только на одном моменте.

Внутри функции imageTtfText() , указан путь к шрифту verdana.ttf . Так вот для корректной работы капчи, мы должны создать папку fonts , и поместить туда файл шрифта verdana.ttf . Его Вы можете найти и скачать из интернета, или взять из архива с материалами данной статьи .

С HTML структурой мы закончили, пора двигаться дальше.

Проверка email на валидность с помощью jQuery

Любая форма нуждается в проверки на валидность введённых данных, как на стороне клиента (с помощью JavaScript, jQuery), так и на стороне сервера.

Особенную внимательность мы должны уделить полю Email. Очень важно чтобы введённый почтовый адрес был валидным.

Для данного поля input, мы задали тип email (type="email"), это нас немножко предостерегает от неправильных форматов. Но, этого недостаточно, потому что через инспектор кода, которого предоставляет нам браузер, можно легко изменить значение атрибута type с email на text , и всё, наша проверка будет уже недействительна.


И в таком случае, мы должны сделать более надёжную проверку. Для этого, воспользуемся библиотекой jQuery от JavaScript.

Для подключения библиотеки jQuery, в файле header.php между тегами , перед закрывающего тега , добавляем эту строчку:

Сразу после этой строчки, добавим код проверки валидации email. Здесь же добавим код проверки длины введённого пароля. Его длина должна быть не меньше 6 символов.

С помощью данного скрипта, мы проверяем введённого почтового адреса на валидность. Если пользователь ввёл неправильный Email, то мы выводим ему ошибку об этом и дезактивируем кнопку отправки формы. Если всё хорошо, то мы убираем ошибку и активируем кнопку отправки формы.

И так, с проверкой формы на клиентской части мы закончили. Теперь мы можем отправить её на сервер, где также сделаем пару проверок и добавим данные в БД.

Регистрация пользователя

Форму мы отправляем на обработку файлу register.php , через метод POST. Название данного файла обработчика, указано в значение атрибута action . А метод отправки указано в значение атрибута method .

Открываем этот файл register.php и первое что нам нужно сделать, это написать функцию запуска сессии и подключить созданный нами ранее файл dbconnect.php (В этом файле мы сделали подключение к БД). И ещё, сразу объявим ячейки error_messages и success_messages в глобальном массиве сессии. В error_mesages будем записывать все сообщения об ошибках возникающие при обработке формы, а в succes_messages , будем записывать радостные сообщения.

Перед тем как продолжить, мы должны проверить, была ли вообще отправлена форма . Злоумышленник, может посмотреть на значение атрибута action из формы, и узнать какой файл занимается обработкой данной формы. И ему может прийти в голову мысль перейти напрямую в этот файл, набирая в адресной строке браузера такой адрес: http://арес_сайта/register.php

Поэтому нам нужно проверить наличие ячейки в глобальном массиве POST, имя которой соответствует имени нашей кнопки "Зарегистрироваться" из формы. Таким образом мы проверяем была ли нажата кнопка "Зарегистрироваться" или нет.

Если злоумышленник попытается перейти напрямую в этот файл, то он получить сообщение об ошибке. Напоминаю, что переменная $address_site содержит название сайта и оно было объявлено в файле dbconnect.php .

Ошибка! главную страницу .

"); } ?>

Значение капчи в сессии было добавлено при её генерации, в файле captcha.php . Для напоминания покажу ещё раз этот кусок кода из файла captcha.php , где добавляется значение капчи в сессию:

Теперь приступим к самой проверке. В файле register.php , внутри блока if, где проверяем была ли нажата кнопка "Зарегистрироваться", а точнее где указан комментарий " // (1) Место для следующего куска кода " пишем:

//Проверяем полученную капчу //Обрезаем пробелы с начала и с конца строки $captcha = trim($_POST["captcha"]); if(isset($_POST["captcha"]) && !empty($captcha)){ //Сравниваем полученное значение с значением из сессии. if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != "")){ // Если капча не верна, то возвращаем пользователя на страницу регистрации, и там выведем ему сообщение об ошибке что он ввёл неправильную капчу. $error_message = "

Ошибка! Вы ввели неправильную капчу

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } // (2) Место для следующего куска кода }else{ //Если капча не передана либо оно является пустой exit("

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

"); }

Далее, нам нужно обрабатывать полученные данные, из массива POST. Первым делом, нам нужно проверить содержимое глобального массива POST, то есть находится ли там ячейки, имена которых соответствуют именам полей input из нашей формы.

Если ячейка существует, то обрезаем пробелы с начала и с конца строки из этой ячейки, иначе, перенаправляем пользователя обратно на страницу с формой регистрации.

Далее, после того как обрезали пробелы, добавляем строку в переменную и проверяем эту переменную на пустоту, если она не является пустой, то идём дальше, иначе перенаправляем пользователя обратно на страницу с формой регистрации.

Этот код вставляем в указанное место "// (2) Место для следующего куска кода ".

/* Проверяем если в глобальном массиве $_POST существуют данные отправленные из формы и заключаем переданные данные в обычные переменные.*/ if(isset($_POST["first_name"])){ //Обрезаем пробелы с начала и с конца строки $first_name = trim($_POST["first_name"]); //Проверяем переменную на пустоту if(!empty($first_name)){ // Для безопасности, преобразуем специальные символы в HTML-сущности $first_name = htmlspecialchars($first_name, ENT_QUOTES); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваше имя

Отсутствует поле с именем

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["last_name"])){ //Обрезаем пробелы с начала и с конца строки $last_name = trim($_POST["last_name"]); if(!empty($last_name)){ // Для безопасности, преобразуем специальные символы в HTML-сущности $last_name = htmlspecialchars($last_name, ENT_QUOTES); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Вашу фамилию

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле с фамилией

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["email"])){ //Обрезаем пробелы с начала и с конца строки $email = trim($_POST["email"]); if(!empty($email)){ $email = htmlspecialchars($email, ENT_QUOTES); // (3) Место кода для проверки формата почтового адреса и его уникальности }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш email

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["password"])){ //Обрезаем пробелы с начала и с конца строки $password = trim($_POST["password"]); if(!empty($password)){ $password = htmlspecialchars($password, ENT_QUOTES); //Шифруем папроль $password = md5($password."top_secret"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш пароль

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } // (4) Место для кода добавления пользователя в БД

Особенную важность имеет поле email . Мы должны проверить формат полученного почтового адреса и его уникальность в БД. То есть не зарегистрирован ли уже какой-то пользователь с таким же почтовым адресом.

В указанном месте "// (3) Место кода для проверки формата почтового адреса и его уникальности " добавляем следующий код:

//Проверяем формат полученного почтового адреса с помощью регулярного выражения $reg_email = "/^**@(+(*+)*\.)++/i"; //Если формат полученного почтового адреса не соответствует регулярному выражению if(!preg_match($reg_email, $email)){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Вы ввели неправельный email

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } //Проверяем нет ли уже такого адреса в БД. $result_query = $mysqli->query("SELECT `email` FROM `users` WHERE `email`="".$email."""); //Если кол-во полученных строк ровно единице, значит пользователь с таким почтовым адресом уже зарегистрирован if($result_query->num_rows == 1){ //Если полученный результат не равен false if(($row = $result_query->fetch_assoc()) != false){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Пользователь с таким почтовым адресом уже зарегистрирован

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка в запросе к БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); } /* закрытие выборки */ $result_query->close(); //Останавливаем скрипт exit(); } /* закрытие выборки */ $result_query->close();

И так, мы закончили со всеми проверками, пора добавить пользователя в БД. В указанном месте " // (4) Место для кода добавления пользователя в БД " добавляем следующий код:

//Запрос на добавления пользователя в БД $result_query_insert = $mysqli->query("INSERT INTO `users` (first_name, last_name, email, password) VALUES ("".$first_name."", "".$last_name."", "".$email."", "".$password."")"); if(!$result_query_insert){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка запроса на добавления пользователя в БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); }else{ $_SESSION["success_messages"] = "

Регистрация прошла успешно!!!
Теперь Вы можете авторизоваться используя Ваш логин и пароль.

"; //Отправляем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); } /* Завершение запроса */ $result_query_insert->close(); //Закрываем подключение к БД $mysqli->close();

Если в запросе на добавления пользователя в БД произошла ошибка, мы добавляем сообщение об этой ошибке в сессию и возвращаем пользователя на страницу регистрации.

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

Скрипт для проверки формата почтового адреса и длины пароля находится в файле header.php , поэтому он будет действовать и на поля из этой формы.

Запуск сессии также происходит в файле header.php , поэтому в файле form_auth.php сессию запускать не нужно, потому что получим ошибку.


Как я уже сказал, скрипт проверки формата почтового адреса и длины пароля здесь также действует. Поэтому если пользователь введёт неправильный почтовый адрес или короткий пароль, то он сразу же получить сообщение об ошибке. А кнопка войти станет не активной.

После устранения ошибок кнопка войти становится активной, и пользователь сможет отправить форму на сервер, где она будет обрабатываться.

Авторизация пользователя

В значение атрибута action у форы авторизации указан файл auth.php , это значит, что форма будет обрабатываться именно в этом файле.

И так, открываем файл auth.php и пишем код для обработки формы авторизации. Первое что нужно сделать это запустить сессию и подключить файл dbconnect.php для соединения с БД.

//Объявляем ячейку для добавления ошибок, которые могут возникнуть при обработке формы. $_SESSION["error_messages"] = ""; //Объявляем ячейку для добавления успешных сообщений $_SESSION["success_messages"] = "";

/* Проверяем была ли отправлена форма, то есть была ли нажата кнопка Войти. Если да, то идём дальше, если нет, то выведем пользователю сообщение об ошибке, о том что он зашёл на эту страницу напрямую. */ if(isset($_POST["btn_submit_auth"]) && !empty($_POST["btn_submit_auth"])){ //(1) Место для следующего куска кода }else{ exit("

Ошибка! Вы зашли на эту страницу напрямую, поэтому нет данных для обработки. Вы можете перейти на главную страницу .

"); }

//Проверяем полученную капчу if(isset($_POST["captcha"])){ //Обрезаем пробелы с начала и с конца строки $captcha = trim($_POST["captcha"]); if(!empty($captcha)){ //Сравниваем полученное значение с значением из сессии. if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != "")){ // Если капча не верна, то возвращаем пользователя на страницу авторизации, и там выведем ему сообщение об ошибке что он ввёл неправильную капчу. $error_message = "

Ошибка! Вы ввели неправильную капчу

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }else{ $error_message = "

Ошибка! Поле для ввода капчи не должна быть пустой.

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } //(2) Место для обработки почтового адреса //(3) Место для обработки пароля //(4) Место для составления запроса к БД }else{ //Если капча не передана exit("

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

"); }

Если пользователь ввёл проверочный код правильно, то идём дальше, иначе возвращаем его на страницу авторизации.

Проверка почтового адреса

//Обрезаем пробелы с начала и с конца строки $email = trim($_POST["email"]); if(isset($_POST["email"])){ if(!empty($email)){ $email = htmlspecialchars($email, ENT_QUOTES); //Проверяем формат полученного почтового адреса с помощью регулярного выражения $reg_email = "/^**@(+(*+)*\.)++/i"; //Если формат полученного почтового адреса не соответствует регулярному выражению if(!preg_match($reg_email, $email)){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Вы ввели неправильный email

"; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Поле для ввода почтового адреса(email) не должна быть пустой.

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле для ввода Email

"; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } //(3) Место для обработки пароля

Если пользователь ввёл почтовый адрес в неправильном формате или значение поля почтового адреса является пустой, то мы возвращаем его на страницу авторизации где выводим ему сообщение об этом.

Проверка пароля

Следующее поле для обработки, это поле с паролем. В указанное место "//(3) Место для обработки пароля ", пишем:

If(isset($_POST["password"])){ //Обрезаем пробелы с начала и с конца строки $password = trim($_POST["password"]); if(!empty($password)){ $password = htmlspecialchars($password, ENT_QUOTES); //Шифруем пароль $password = md5($password."top_secret"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш пароль

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле для ввода пароля

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); }

Здесь мы с помощью функции md5() шифруем полученный пароль, так как в БД пароли у нас находятся именно в зашифрованном виде. Дополнительное секретное слово в шифровании, в нашем случае "top_secret " должна быть та которая использовалась и при регистрации пользователя.

Теперь необходимо сделать запрос к БД на выборке пользователя у которого почтовый адрес равен полученному почтовому адресу и пароль равен полученному паролю.

//Запрос в БД на выборке пользователя. $result_query_select = $mysqli->query("SELECT * FROM `users` WHERE email = "".$email."" AND password = "".$password."""); if(!$result_query_select){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка запроса на выборке пользователя из БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); }else{ //Проверяем, если в базе нет пользователя с такими данными, то выводим сообщение об ошибке if($result_query_select->num_rows == 1){ // Если введенные данные совпадают с данными из базы, то сохраняем логин и пароль в массив сессий. $_SESSION["email"] = $email; $_SESSION["password"] = $password; //Возвращаем пользователя на главную страницу header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/index.php"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Неправильный логин и/или пароль

"; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }

Выход с сайта

И последнее что мы реализуем, это процедура выхода с сайта . На данный момент в шапке у нас выводятся ссылки на страницу авторизации и на страницу регистрации.

В шапке сайта (файл header.php ), с помощью сессии мы проверяем, авторизован ли уже пользователь. Если нет, то выводим ссылки регистрации и авторизации, в противном случае (если он авторизован) то вместо ссылок регистрации и авторизации выводим ссылку Выход .

Модифицированный кусок кода из файла header.php :

Регистрация

Выход

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

Код файла logout.php:

На этом всё. Теперь Вы знаете как реализовать и обрабатывать формы регистрации и авторизации пользователя на своём сайте. Эти формы встречаются почти на каждом сайте, поэтому каждый программист должен знать, как их создавать.

Ещё мы научились проверять вводимые данные, как на стороне клиента (в браузере, с помощью JavaScript, jQuery) так и на стороне сервера (с помощью языка PHP). Также мы научились реализовать процедуру выхода с сайта .

Все скрипты проверены и рабочие. Архив с файлами этого маленького сайта Вы можете скачать по этой ссылке .

В будущем я напишу статью где опишу . И ещё планирую написать статью где объясню, (без перезагрузки страницы). Так что, для того чтобы быть в курсе о выходе новых статей можете подписаться на мой сайт.

При возникновении вопросов обращайтесь, также, если вы заметили, какую-то ошибку в статье прошу вас, сообщите, мне об этом.

План урока (Часть 5):

  1. Создаем HTML структуру для формы авторизации
  2. Обрабатываем полученные данные
  3. Выводим приветствие пользователя в шапку сайта

Понравилась статья?

Login forms are everywhere on the web. Are you using the social networks? You must go through login form of some sort. Do you have an email? Did you join any forums? Did you try to leave a comment on a WordPress site? To gain access to anything on the internet, the chances are you will have to go through some sort of login process. You will probably have to register first, sign up or leave some information behind. You will have to use some sort of login form to do anything on the internet.

So what do Login Forms have to do with HTML and CSS? They are both the essential parts of the Login Forms.

HTML (HyperText Markup Language) is a standard markup language used to create web pages. HTML elements are building blocks of all websites.

CSS (Cascading Style Sheet) is a language used for describing the look and formatting of a document written in a markup language. Such as HTML!

We use HTML to build a website and CSS to make it look nice. That is what most of the users encounter while browsing the web.

We’ve made a list of 50 free login forms that you can use on your WordPress site, blog, forum or anywhere else. This is a hand-picked list by Colorlib to ensure the highest quality of the forms. Each and every form has been thoroughly tested to ensure no components are missing and source code is available with every download. Of course, you are free to use these forms for personal and commercial purposes, with no need for attribution.

Explore 2.5 Million Digital Assets including 2019’s Best WordPress Templates

2M+ items from the world’s largest marketplace for HTML5 Templates, Themes & Design Assets. Whether that’s what you need, or you’re just after a few Stock Photos – all of it can be found here at Envato Market.

DOWNLOAD NOW

WordPress Login Customizer

The rest of the list and HTML/CSS powered login forms but here you can see the best login customizer plugin for WordPress. It comes with several defined templates that you can further tweak to match the design of your website. Thats to this plugin you can finally get rid of boring WordPress wp-admin page and create a truly unique experience for yourself and your users.

Download

Creative Login Form

Simple yet creative login form created using HTML5 and CSS3. This form can be used as registration form as well. This is our favorite template on this list thanks to its flexibility and similarity that allows you to create

WordPress version

We did search the internet for cool login forms but it was very difficult to find good looking ones therefore we decided to have our take on them. We would like to present 20 login forms designed and developer by Colorlib team.

Login Form 1 by Colorlib


Simple, creative and vibrant login form with a gradient background. You can use this one for all sorts of intentions, like web, mobile or desktop applications. But do get creative with it if you like.

WordPress version

Login Form 2 by Colorlib


Minimal and sophisticated login form by Colorlib with a gradient button with animation and a logo. Use it, alter it and have it as a nice addition to your already nifty web space.

WordPress version

Login Form 3 by Colorlib


A gorgeous login page with a background image with shadow and a gradient form box with login button hover effect. The only limitation that you have is your imagination, so expand your view and use Login Form 3 to its full potential.

WordPress version

Login Form 4 by Colorlib


Creativity knows no limits and nor does Login Form 4. Here it is, at your disposal, ready and set for you to download it and put it to some good use. Do not worry about the responsiveness either.

WordPress version

Login Form 5 by Colorlib


Gorgeous, clean and modern form with an option to log in with Facebook or Google. All buttons have a nice hove effect that spices up the experience.

WordPress version

Login Form 6 by Colorlib


If your page is already super neat and tidy, a login form should be no different. Here is one that will easily meet your expectations if minimalism is your cup of tea.

WordPress version

Login Form 7 by Colorlib


A form with a three-way option of logging into the account. Either it is Facebook, Twitter or email login they prefer, this is the type of a tool that you need to feature on your page. And if they do not already have an account, you can also link it with your sign up page.

WordPress version

Login Form 8 by Colorlib


Another contemporary, trendy and enticing login form with rounded everything. This one is especially applicable to mobile users due to its currently very popular rounded corners style.

WordPress version

Login Form 9 by Colorlib


If you would like to avoid the white or single-color background, this is the login form page that you should consider. Not only does it support a full image background, but it also comes with a gradient overlay and an option to log in with Facebook or Google.

WordPress version

Login Form 10 by Colorlib


A somewhat complete opposite compared to the previous one is Login Form 10. It almost could not be more minimalistic looking while still having this up-to-the-minute feel to it.

WordPress version

Login Form 11 by Colorlib


With our collection of the best HTML5 and CSS3 login forms, you save yourself time and effort (money, too). Instead of building one from scratch, here is another killer ready-to-use template for you to employ.

WordPress version

Login Form 12 by Colorlib


Image background with a blue shadow overlay, name, image and the must-have form, that’s what’s up with Login Form 12. There is also a cool hover effect on the login button and gives you a chance to link it with your registration form for all new users.

WordPress version

Login Form 13 by Colorlib


A split screen sign up form, where one half is dedicated to an image and the other half to the form. It is a free tool which you can start using this very moment. Just download the layout and go full tilt with it.

WordPress version

Login Form 14 by Colorlib


In this collection, we have a mixture of simplistic and those a tad more complex and advanced login forms. In short, there is something for everyone and Login Form 14 is more on the minimalistic side. But why even complicate with a login form, right? To each their own.

WordPress version

Login Form 15 by Colorlib


While still keeping things to the bare minimum, one cool addition to the Login Form 15 is the image banner just above the form. With this little feature, you can make the experience slightly more engaging.

WordPress version

Login Form 16 by Colorlib


This is a login form with a full-screen image on top of which is placed a form with username and password fields and a gradient button with hover effect. Simple and straightforward.

WordPress version

Login Form 17 by Colorlib


To make it appear more personal, this framed login form template is the best fit for you. It has an image side and a form side but keeps things to the very minimum while still ensuring professionalism.

WordPress version

Login Form 18 by Colorlib


If you like to differentiate yourself and keep things original, do consider using Login Form 18. While some enjoy login pages super basic, the others want to have some additional goodies rocking the layout. And if adding a picture is what you are after, this one is for you.

WordPress version

Login Form 19 by Colorlib


Vibrant, energetic and attention-grabbing, that is what this next login form based on HTML5 and CSS3 is all about. It is also fully responsive and mobile-ready, as well as compatible with all major web browsers.

WordPress version

Login Form 20 by Colorlib


Gradient background, black sign in button with hover effect, username and password fields along with custom text and “Forgot password?” section, yep, that’s all part of Login Form 20. Sounds overwhelming but in reality, far from it.

WordPress version

The form is hidden unless you click on “Login” option. Really great feature for modern websites that want to avoid having a separate page for the login form. You can display the form anywhere on your website with this powerful tool.

Download

A design for a Sign Up form using tabs and floating form labels.

Download

What was initially made to stop people from entering one person’s WordPress site, it became a really popular form due to its simplicity and neat design.

Download

Flat Login – Sign Up Form

Once you click “Click me” button in top-right corner, you will get smooth animation that transforms this Login form to Sign up form.

Download

Login With Self-Contained SCSS Form

This is a form with self-contained SCSS. An extension of CSS that adds power and elegance to the basic language. It allows to use variables, nested rules, mixins, inline imports, and more.

Download

This is actually an animated Login form, with top “Hey you, Login already” transforming into the form at the bottom. Smooth animation effects.

Download

This is an example on how to create a simple login form using HTML5 and CSS3. This form uses pseudo elements (:after and:before) to create the multi page effect. These elements are rotated using the CSS3 transform property. This form uses HTML5 to make validation and submission easy.

Download

Once you enter a wrong password in this form, a nice shake effect will warn you that you did not enter the correct password. A simple and effective solution that will point out the problem of incorrect passwords.

Download

A boxy login form with a little surprise. Try “admin” as a username, and “1234” as a password, for full experience.

Download

Neat little login form. Once you click on “LOGIN” on the left side, animation effect creates neat little login form on the right. Definitely unique approach!

Download

Material Design Form


Fairly simple and easy on the eye login form that you can add to your blog or any other website and spice up the experience. No need to overcomplicate with a simple thing as the login form is. Even if you are just collecting subscribers, you can also play around with this layout and get things rocking.

Download

Bootstrap Snippet Form


Obviously, this next free HTML5 login form is based on the well-liked Bootstrap Framework. This tells you that you can expect some nice flexibility that any modern website and element must practice. Email address, password and a check box to tick if a user would like the platform to remember his or her information. Easy and to the point.

Download


Regardless of your main web design, with things like login forms, you do not want to over complicate it. Instead, you would want to keep it simple and let it to the job, getting users to access their accounts seamlessly. You will achieve that goal with this login form with flat UI unquestionably.

Download

Trendy UI Kits Form


From super simple login forms to those with slightly more action going on. This particular one is pretty similar compared to the last one just that you will notice a frame going all around the form. Get them to type in their names or usernames and passwords and they can enter your world of amazingness.

Download

Dashboard CSS3 HTML5 Form


All the HTML5 and CSS3 login forms you find on this list are simple to use and effortless to attach to your web platform. This one even has a “Forgot your password?” right at the bottom for everyone who just cannot recall their passwords. The template is perfect for entering your dashboard, but you can apply it for other needs, too.

Download

Login With Recovery Form


The title pretty much says it all; this is a neat, clean and minimal looking login form with recovery. What you also notice is that there is no traditional “box” that you are used to seeing login forms use. If you would like to make a difference, you now know which layout to choose.

Download


A free flat login form with a stunning and elegant dark layout coupled with a green call-to-action button. Sure, you can alter the tool to your likings, but you can also employ it exactly as is and have it live on your website in a snap. Play around with its features and have it all set up the way you like it.

Download

Transparent Login


Even a login form can be of super creative and attention-grabbing nature. While many stick to the simple and basic look, there are others who like it special and exclusive. This transparent login form will surely do the trick for you. With an image background and a form over it, this layout can follow your branding to a T.

Download


No need to be really going too in-depth with this next login since it is pretty self-explanatory. It is compatible with the Google Chrome extension, as well as features buttons for those who are not signed up yet or lost their password. If this is the one you were looking for, then scrolling all the way this far was more than worth it.

Download

Elegant Flat Form


A stylish flat form which you can append to your web space as a pop-up or ad as a widget on a page. Whatever the case, it will keep your professional approach intact. It is simple and easy on the eye and also has a CTA for everyone who missed signing up to your members’ area. Use it as is or improve it according to your taste.

Download


Definitely an approach to a free login form that you should not miss. It has a feel of a coupon just that it is not if that even makes any sense. Anyhow, in the text section, you can also link this form to the signup form for those interested in creating an account. Other than that, it surely will capture their attention.

Download


More and more website owners are implementing social logins and you can join the trend as well. This free login form with social integration is the right option to take the plunge. However, along with Twitter, Facebook and Google+ buttons, the layout also features the traditional way of signing up with an email.

Download


If your password is super complex, you sometimes just want to enter it in a “show” mode. Offer this same feature to all your users with the show and hide password login form. It has a stunning dark layout with green details perfect for those who dig this type of designs. Of course, feel free to make changes to it and fine-tune it according to your needs.

Download

Log ‘N Load Animated Form


If you already practice animations and special effects on your page, keep the trend with the login form, too. Instead of creating your own one, you can simply use this striking Log ‘N Load animated form that will do the trick. Once you hover over the login button, the form reveals right in front of you. It even has a circular loading that enhances the experience.

Download


This flat, modern and easy to use login form works great on all devices, mobile, tablet and desktop. You can also play around with different tweaks and alter the default settings to your website’s style precisely. The tool also has cool hover effects that add a touch of sophistication to the overall experience.