Правильный registration form html. Форма входа и регистрации с помощью HTML5 и CSS3

In this tutorial, we are going to tell you how you can create Registration Form using HTML and CSS3. We will create two Registration forms; the first one is simple, and another one has Icons with each input field. The icons we have used are font icons. These registration form s are simple, clean and attractive.

The icons we have used are font icons. These registration forms are simple , clean code and unique in design. You can be utilized it into your website and customize it as you need.

If you are looking for more forms collection, then this 40+ beautiful sign-up forms is the best collection I found on the internet. They posted a lot of forms free and premium as well.

The signup forms used on websites to allow the site visitors to create an account and build their profile. It depends on upon you what benefit you will give to the users who register on your website.

Some site used such form to provide more access to the user such as download files or post article etc. Anyway, Let’s have a look, how we can create them.

Registration Form in HTML

Let’s start with registration form HTML code. Both forms code added inside the div class name cclogin .

For simple form, we have added class simple next to cclogin and for icon style form , we have added class icons next to cclogin .

The input fields of the form are inside the p tag. let’s have a look block of HTML code.

Let’s add some placeholders

But if you see the demo, I have to make the first name and last name fields small and fit them into one row. To make them like that we have added half class into p the tag.

As I said you before that, another Form is icon style form. In this form, we have used a similar technique which we have previously used in As you know we are using font icon so we have added it to span tag.

Forms Styling with CSS

First of all, we will take a look at style-sheet of icons. For icons, we have used:before attribute

Fa-user:before { content: "\f007"; } .fa-key:before { content: "\f084"; } .fa-envelope:before { content: "\f0e0"; }

Let’s see styling of the fields

Cclogin input, .cclogin input, .cclogin select{ padding:10px; width:100%; border:none; height:50px; line-height:50px; color:#757575; }

The form fields without icons have 100% width, but for the fields without have 92% width, this is because we require space to add icons before the input fields.

To make the fields small, we just have added class .half into p the tag and set it’s width to 48%. For second field we have added .last class next to .half class so we can make the margin-right:0%; in the CSS.

Cclogin .half { float: left; width: 48%; margin-right:4% } .cclogin .half.last{ margin-right:0%; }

The icons used in the demo are from the Font Awesome set by Davegandy and they are licensed under the CC BY 3.0 license. Hope you enjoy this CSS3 user register Form. Leave the comment to let us know.

Here is an example of Registration form using HTML. Here a programmer can display as many "Text Field" as he/she wants. The name in front of Text Field is called "Label". At the end of the registration form their is a "ADD" button behnd which any desired link can be used. Once clicked it will redirect to that particular destination.

Here is an example of Registration form using HTML. Here a programmer can display as many "Text Field" as he/she wants. The name in front of Text Field is called "Label". At the end of the registration form their is a "ADD" button behnd which any desired link can be used. Once clicked it will redirect to that particular destination.

HTML Code for registration form

Here is an example of Registration form using HTML. Here a programmer can display as many "Text Field" as he/she wants. The name in front of Text Field is called "Label". At the end of the registration form their is a "ADD" button behnd which any desired link can be used. Once clicked it will redirect to that particular destination.

In this example we have shown 9 "Text Field". Size of the Text Box can also be changed as per the requirement.

registration.html

registration form

Registration form

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() { if(!isset($_POST["submitted"])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; }

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,"email")) { $this->HandleError("This email is already registered"); return false; } if(!$this->IsFieldUnique($formvars,"username")) { $this->HandleError("This UserName is already used. Please try another username"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; }

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR(128) NOT NULL ,". "email VARCHAR(64) NOT NULL ,". "phone_number VARCHAR(16) NOT NULL ,". "username VARCHAR(16) NOT NULL ,". "password VARCHAR(32) NOT NULL ,". "confirmcode VARCHAR(32) ,". "PRIMARY KEY (id_user)". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; }

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query($insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; }

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email"])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n". "$confirm_url\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; }

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub .

Welcome back UserFullName(); ?>!

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.

Для обмена данными между компьютером пользователя и сервером в HTML применяются формы . Обычно обмен данными происходит следующим образом: пользователь вводит требуемые данные в поля формы, после чего они отправляются на сервер, где обрабатываются соответствующей программой. Если это, например, регистрационные данные пользователя, то они проверяются на соответствие предъявляемым требованиям и, в случае успешной проверки, заносятся в базу данных. Пользователю при этом возвращается ответ, в котором либо сообщается об успешном завершении регистрации, либо предлагается возможность исправить ошибки, допущенные в ходе заполнения полей формы. Конечно, применение форм не ограничивается только лишь сбором данных от пользователей и передачей их на сервер для обработки, однако данное предназначение следует считать основным.

Тег
и его атрибуты

Формируется элемент "form" при помощи парного тега и представляет собой контейнер, в котором расположены элементы формы: поля ввода, кнопки и т.д., которые мы подробно рассмотрим в следующих пунктах. Сейчас же перечислим атрибуты элемента "form" .

  • name - определяет уникальное имя формы, которое в основном используется для доступа к ней через скрипты.
  • action - в качестве значения принимает полный или относительный путь к серверной программе-обработчику, которой будут передаваться данные формы после отправки на сервер.
  • target - принимает в качестве значения имя окна или фрейма, в который будет загружаться html -страница, возвращаемая серверной программой-обработчиком после обработки пользовательских данных. Напомним, что в качестве зарезервированных имен атрибут target может принимать ряд значений, которые уже перечислялись ранее .
  • enctype - устанавливает способ кодирования отправляемых данных. Может принимать значения:
    • "application/x-www-form-urlencoded" - применяется по умолчанию и подходит для большинства случаев, поэтому сам атрибут enctype обычно не указывается;
    • "multipart/form-data" - следует использовать при отправке файлов;
    • "text/plain" - кодирует данные в виде простого текста, только заменяя пробелы знаком "+" ; требуется редко, например, может быть полезен при отправке данных формы по электронной почте.
  • novalidate - отменяет встроенную проверку данных вводимых пользователем в поля формы на ошибки. Значений не принимает и по умолчанию выключен.
  • autocomplete - позволяет отключать автозаполнение полей формы, которое происходит при повторном вводе одинаковых данных. Принимает два значения "on" (по умолчанию) и "off" . При этом, если автозаполнение отключено в настройках самого браузера, то данный атрибут игнорируется. Кроме того, значение атрибута может быть переопределено таким же атрибутом autocomplete , но у конкретных элементов формы, например, в случае необходимости не сохранять важные данные вроде паролей, номеров банковских карт и т.д.
  • accept-charset - указывает кодировку символов передаваемых данных, например, "utf-8" . Если атрибут не указан, то указывается кодировка, установленная для страницы.
  • method - принимает значения "GET" или "POST" , которые определяют метод отправки данных формы на сервер. По умолчанию применяется "GET" .

Чтобы иметь визуальное представление о форме, давайте посмотрим на пример 6.1.

Формы



Пример 6.1. Использование элемента "form"

Загрузка...
Top