Как сделать личный кабинет на сайте html
Перейти к содержимому

Как сделать личный кабинет на сайте html

  • автор:

Tutorial to create a login system using HTML, PHP, and MySQL

This is a tutorial for creating a login system with the help of HTML, PHP, and MySQL. Your website needs to be dynamic and your visitors need to have instant access to it. Therefore, they want to log in as many times as possible. The login authentication system is very common for any web application. It allows registered users to access the website and members-only features. It is also helpful when we want to store information for users. It covers everything from shopping sites, educational sites, and membership sites, etc.

This tutorial is covered in 4 parts.

Table of Contents

1) Building a Signup system

In this part, We will create a signup system that allows users to create a new account to the system. Our first step is to create a HTML registration form. The form is pretty simple to create. It only asks for a name, email, password, and confirm password. Email addresses will be unique for every user. Multiple accounts for the same email address are not allowed. It will show an error message to the users who try to create multiple accounts with the same email address.

Step 1: Creating Registration Form in HTML

We will create a PHP file named register.php with the following code in it. This is a simple HTML form with some basic validation. If you are not familiar with HTML then you can get it from many online sites who give ready-made html5 login form templates.

The output of the above HTML form will look like this.

Sign Up

All the input fields are required by adding the «required» attribute which is the default HTML attribute. The use of type=»email» will validate the email address provided by users and gives an error if the email address is not valid. For the registration form, we have used bootstrap for rapid development. If you want to save your time on HTML code you can always use some free html5 templates for your project.

Step 2: Creating the MySQL Database Table

You will need to create a new database with any suitable name you want. After that please execute the below SQL query to create the user’s table inside your newly created MySQL database.

Step 3: Creating Database Configuration File

Now, we have created the users table. Let’s create a new PHP file named config.php to connect with the MySQL database. Paste the following code in the config.php file and change the database name to whatever you choose while creating the database.

Step 4: Creating a Session File

Let’s create a file named session.php. In this file, we will start the session and check if a user is already logged in, if yes then we will redirect the user to welcome.php file.

Step 5: Create Registration Form in PHP

Finally, it’s time to create a PHP code that allows users to register their accounts into the system. This PHP code will alert users with an error if any user is already registered with the same email address.

Replace the following code in the register.php file.

Once user click on submit button it will check if $_SERVER[«REQUEST_METHOD»] == «POST» and $_POST[‘submit’] variable has been set. For security concerns, we always suggest not to store the password as plain text in the database. We have used password_hash() function which creates a new password hash using a strong one-way hashing algorithm.

The above PHP script will validate that no user is registered with the same email address and also validate password. After validation is confirmed we store the user-provided information in the users’ table and alert the user that registration was successful.

2) Building a Login System

In this part, we will create a login form to allow users to access the restricted area of the system. In our case, the restricted area is a welcome page which we will cover in the next part.

Step 1: Creating a Login Form in HTML

Below is the Login Form in HTML. Paste it in a file named login.php

The output of the above code will look like this

Login

Step 2: Creating a Login System in PHP

After creating the login form in HTML, we will write a code to validate login credentials. On form submit we will check that the email and password are filled. If they filled then we will execute a SELECT query to find the record in a database on the basis of email and password. If any record found, then we will store the «userID» in session and the user is redirected to the welcome.php file, otherwise, the user is alerted with an error message.

Let’s replace the following code in the login.php file.

3) Creating a Welcome Page

Below is the code for the welcome.php file. Users will be redirected to this page after a successful login process. We have added some code at the top of the page to check if the user is not logged in, then redirect the user to the login page.

Let’s create a welcome.php file and paste the following code in it.

4) The Logout script

Finally, Let’s create a logout.php file with the following code in it.

Once the user clicks on the Log Out link, the above script, will be called to destroy the session and redirect user to the login.php file.

Conclusion

In this tutorial, I explained how you can create a Login System using HTML, PHP and MySQL. Once you understand how simple it is to create a login system you can add other features like reset password, forgot password, verify email address, edit user’s profile, etc.

Форма входа в личный кабинет

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

Пример формы входа

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

  • высокий показатель кроссбраузерности;
  • правильно написанный код с точки зрения семантики;
  • отсутствие каких-либо конфликтов с запоминалками паролей;
  • хорошая читабильность кода.

Решение поставленной задачи с помощью Javascript

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

Начинаем с создания HTML-кода. Для начала хочу Вас ознакомить с особенностями написания HTML, чтобы было понятно что и зачем написано в коде:

  1. Подписи полей логин и пароль необходимо делать не внутри тега input, а через label. Это будет правильно с точки зрения семантики нашего кода. В тоже время соответствует общепринятым правилам создания форм, что обеспечит легкое понимание кода и простоту его чтения.
  2. Название наших полей (содержимое label) нужно абсолютным позиционированием установить над самим полем. То есть тег label будет лежать поверх тега input. Таким образом мы экономим место для формы и реализуем одну из поставленных нами задач. Абсолютное позиционирование задается с помощью свойства position и значения absolute для него.
  3. Воспользуемся событием onfocus, благодаря которому текст названия будет исчезать при наведение на поле.
  4. Для того, чтобы сохранить адекватность работы с запоминалками полей необходимо наладить их анализ при загрузке. Если поля не пустые, то текст тегов label должен быть удален.

Таким образом, мы подошли непосредственно к самому HTML-коду, который должен выглядеть следующим образом:

Видео заточка цепей, заточка цепей для бензопил.

Заметка!
Очень важно, чтобы для label был прописан атрибут for, значение которого соответствует идентификатору input. Это позволяет избежать трудоемкой и не нужной процедуры ручного перевода фокуса для конкретного поля.

После этого необходимо заняться написанием кода Javascript. Пример приведен на основе фреймворка jQuery, однако не стоит паниковать, так как при желании можно корректировать код в соответствии с другими фреймворками. Для этого не нужно много ума и времени, так как алгоритм действий сохраняется

Единственным недостатком такого решение является то, что применяется Javascript. Существуют еще пути решения данной задачи:

  1. Добавить динамическое поле пароля с атрибутом type и значением password.
  2. Изменение подписей с помощью фоновых изображений.

Динамические поля

Суть данного метода заключается в создании двух полей с указанием текстового типа (type=»text»). В этих же полях прописываем атрибут value, значением которого будет название поля. Таким образом, мы получим название поля, которое будет в нем выводиться. Для очищения значения поля используем тот же принцип, что и в первом методе. При назначении фокуса очищаем поле. Для поля пароля необходимо наладить замену текущего типа на password.

Данный метод имеет право на жизнь, но необходимо знать его основные недостатки:

  • не соблюдение семантики;
  • усложнение записи скрипта;
  • осложнение в чтении кода, так как изначально полю пароля присвоен текстовый тип.

Решение на основе фоновых изображений

Принцип работы этого метода полностью идентичен первому способу. Единственное отличие заключается в том. Что вместо тега label используют бекграунд для тега input. Далее алгоритм сохраняется: при получении фокуса свойство background получает значение none.

✨Build a Login and Register Form with HTML and CSS✨

image
Photo By unsplash.com

In this article, today we will learn how to build a simple but aesthetic Login and Register Form.

Simple Login and Register Form

You can access the full code here and the demo page here!

Table of Contents

  1. Gather Resources
  2. Getting Started with Fire-UI
  3. Start building your Landing Page
    • Setup Fire-UI
    • Create Navigation Bar (Navbar)
    • Create Login and Register Form

1. Gather Resources

Before we continue further, some resources you might need before we start coding ��‍����‍�� :

  • Basic knowledge of HTML
  • Text Editor (Either Visual Studio Code or Sublime Text is recommended)
  • A Search Engine (Google, Mozilla, etc will be fine)

So that’s all for our resources, and I believed that you have downloaded all these resources. If haven’t, you can open the link provided above.

2. Getting Started with Fire-UI

Fire-UI is a CSS Library allowing for easier and more standards-compliant web design.

You can read the following blog to know more about Fire-UI

stanleyowen

Fire-UI : A User-Friendly and Reliable CSS Framework

Stanley Owen ・ Dec 19 ’20 ・ 1 min read

To keep it simple and fast, we will move on to the next part.

3. Start building your Landing Page

a. Setup Fire-UI

Now open your text editor and type the basic of HTML:

Exit fullscreen mode

Save the following files with index.html , then we will start setting up Fire-UI. There are some methods to configure and connect Fire-UI. But in this tutorial, we will keep it simple, which is using CDN through jsdelivr :

Exit fullscreen mode

Thus, your index.html will now look like this:

Exit fullscreen mode

After that, save the file as .html extension like the picture below:
HTML Extension

Find the file that you have just save it recently, run it with your default browser and you will see the result like this:
Result

Before continuing further, you can access our full code in the following link: here

Now what we are going to to is to create navigation bar (navbar). If you didn’t sure what is navbar, here is how navbar look like:
Navbar

So what we need is:

  1. Remove the content of body
  2. Add the attribute theme = ‘light’ in the body element
  3. Copy and paste the Navbar code

Exit fullscreen mode

b. Create Login and Register Form
Then we come to the challenging part, which is building the login and register form.

Copy these code to your text editor:

Exit fullscreen mode

Well, we are not done yet, we will create a custom CSS to make it more aesthetic. Now we will create a index.css file which contains the following code:

Exit fullscreen mode

And we are done with our simple login and register template!

Don’t forget to give a star on GitHub if you like this article!

Happy Coding! ��

You may also like these articles:

stanleyowen

Todo Application — An Open Source and Easy to Use Web Application

Stanley Owen ・ Feb 7 ・ 1 min read

kimlimjustin

AbstractMark, the modern markdown language.

Justin Maximillian Kimlim ・ Feb 15 ・ 2 min read

stanleyowen

Build an Awesome Profile Page with Fire-UI

Stanley Owen ・ Jan 19 ・ 13 min read

Top comments (6)

grahamthedev profile image

Don’t forget to use <label> s for your inputs and make sure they are properly associated (this is important for screen readers). You have done this with your checkbox correctly you just need to implement it on your inputs.

Also you don’t need to use <input type=»submit» anymore, a simple <button> will do the trick and make your markup cleaner.

Taking the time to focus on semantics will make your life as a developer much easier and learning good habits now will make you 10x better than most developers in no time looking at what you have done as a student, as this is 100 times better than what I would have done!

kimlimjustin profile image

First of all, Stanley Owen and I appreciate your taking the time to write this comment. As developers of Fire UI, we actually focus more on the main library than the examples making the examples somehow written in not up-to-date HTML tags, we are really sorry for this negligence. Of course, we’ll update this soon. Another factor of this causing is indeed Stanley Owen and I are both junior high school student making us, developers of Fire UI can only googling for learning, and as you know, today technology is evolving everyday and sometimes the query of Google shows up the result coming from the past years, which are maybe not relevant nowadays.

Of course, any contributions like Opening issues like this on GitHub, opening PR, using this Fire UI on your project, or even star it on GitHub, if you will, will be much appreciated.

fire-ui / fire-ui

A user-friendly and reliable CSS library

Fire UI

NPM

Table of Contents

Quick start

There are several quick start options available:

Bug and feature requests

Have a bug or a feature request? please open an issue if your problem or idea is not addressed yet.

Contributing Guidelines

Thanks for your interest in contributing to Fire UI! Please take a moment to review this document before submitting a pull request.

Login and Registration Form in HTML CSS and JavaScript

Hello friend I hope you are doing awesome. Today here we will learn to create a Responsive Login and Registration Form in HTML CSS and JavaScript. You can also check out the 16 Free Login & Registration Forms that I have created to date. But this project has several facilities and features.

The login form is the section on the webpage where users need to fill required details to enter the particular website or webpage. Same as the Registration form is the section with a combination of input fields where users need to fill in details to create a login id and password.

Let’s have a quick look at the given image of our project [Login and Registration Form]. On the left side, we can see a login form with some input fields, buttons,s, and text with links, similarly, on the right side, we can see a registration form. Actually, at first, there will be one form which is the login form and when we click on the signup now button the login form will disappear and the registration form will appear.

Now we are going to watch the real demo of this project [Login and Registration Form], and all the animation that I have included in this template. Also by watching the video tutorial, we will get an idea, of how all HTML CSS and JavaScript code works properly behind this beautiful form design.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *