Bootstrap Example

Ajax Login form using PHP and MySQL

Today I would like to show you Ajax login functionality implementation using PHP and MySQL. We gonna use the MySQL PDO driver in this tutorial. PDO has a much nicer interface, you will end up being more productive, and write safer and cleaner code.

Create Ajax Login Form

Login Form

Create a file called login_form.php with the following code.

 

Login Page

Login

Database Details

This tutorial assumes that you have the following user table structure in your database. For the sake of the example script, I have provided an insert query with test data.

CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `first_name`, `last_name`, `email`, `password`, `date_added`) VALUES (1, 'Arjun', 'PHP', '[email protected]', '$2y$10$8mVSGv/bIGgcvCikXBPfTu7HfXMl3jqfiirtQGyRwV5bvOzNGmmLG', '2017-10-12 18:09:10');

You can generate password hash by using password_hash() function, example echo password_hash(«password», PASSWORD_DEFAULT); .

Config.php

After importing the above table into your database. Create a file called config.php, where you gonna save information about MySQL Database configuration, you can use this file to save other config details too.

Login

Create a file called login.php with the following code. This file will handle the login requests, It will validate user details against the database. Upon valid and successful login, it will start the user session, otherwise, it will throw the appropriate error message.

 if (empty($_POST['password'])) < $error[] = "Password field is required"; >if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) < $error[] = "Enter Valid Email address"; >if (count($error) > 0) < $resp['msg'] = $error; $resp['status'] = false; echo json_encode($resp); exit; >$statement = $db->prepare("select * from users where email = :email"); $statement->execute(array(':email' => $_POST['email'])); $row = $statement->fetchAll(PDO::FETCH_ASSOC); if (count($row) > 0) < if (!password_verify($_POST['password'], $row[0]['password'])) < $error[] = "Password is not valid"; $resp['msg'] = $error; $resp['status'] = false; echo json_encode($resp); exit; >session_start(); $_SESSION['user_id'] = $row[0]['user_id']; $resp['redirect'] = "dashboard.php"; $resp['status'] = true; echo json_encode($resp); exit; > else

secure.php

Create a file called secure.php file with the following code. On successful login, we will redirect the user to this page. Only authenticated users can access this page. If unauthorized users try to access this page, users will forcefully be redirected to the login page.

logout.php

Create a file called logout.php and put the below code in the file.

Once everything is in place head over to the browser with http://localhost/login_form.php you should get output something like the below image

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face — we are here to solve your problems.

Источник

Регистрация на PHP, AJAX, MYSQL

Добрый день друзья, продолжаю небольшую серию уроков по PHP и AJAX, сегодня у нас написание простой системы регистрации пользователя. В данной статье мы будем использовать PHP, MySQL(PDO), JavaScript. Урок рассчитан на новичков, потому я не буду использовать ООП и сторонние пакеты, а наоборот покажу как на чистом PHP написать регистрацию. Для обработки формы регистрации мы будем использовать javascript, отправляя запрос на сервер и получая ответ. Давайте приступим.

Архитектура проекта

Архитектура проекта у нас очень простая. Мы имеем в корне index.php , это будет страница с формой регистрации, на ней же будем выводить список зарегистрированных пользователей. bootstrap.php — файл в корне, в который мы будем подключать файлы для работы с базой данных, наши функции и т.д., а он в свою очередь будет подключен в index.php .

Форма регистрации

В файл index.php вставим следующий код:

В этот файл мы подключаем библиотеку стилей bootstrap, а так же sweetalert — библиотека для красивых уведомлений и конечно же jQuery)

Отправка формы

Для отправки формы регистрации нам нужен javascript. Создадим папку assets/js и в ней файл form.js, вставляем следующий код в файл:

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

Дополнительные файлы

bootstrap.php

Ничего особенного, место в котором стартует приложение и подключаются файлы с функциями и т.д.

db.php

Написал минимальное количество функций для работы текущего приложения.

function get_connection — подключение к базе данных.
function insert — вставка данных в таблицу.
function getUserByEmail — ищем пользователя по имейлу.
function getUsersList — получаем список пользователей.

functions.php

Файл в котором выполняем регистрацию пользователя и валидацию входных данных с формы.

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

Весь проект я сделал в докере и приложил файлы конфигурации, потому проблем с запуском быть не должно. После запуска проекта вы можете открыть в браузере http://localhost:8080 и должны увидеть страницу регистрации.

Если какие-то поля были заполнены не верно, вы получить вот такую форму

Источник

Registration Form using Ajax, PHP & MySQL

If you want to create a registration form that will not reload after submitting the registration details. Then you should make the ajax registration form with PHP & MySQL.

The Ajax Registration form is very useful to process the registered data quickly to the database without refreshing the web page. So. It is frequently used in most of web applications to make their registration form userfriendly & attractive.

In this tutorial, I have shared some simple steps to create the registration/signup form using jquery ajax in PHP & MySQL. Once you learn it you can create any type of other registration forms.

Steps to Create Ajax Registration Form with PHP & MySQL

Now, Let’s start the coding to create the ajax registration form with the following simple steps –

1. Create Registration Form Directory Structure

First of all, You should create the following directory structure to build the registration form.

source-code/ |__database.php |__ajax-script.php |__php-script.php |__index.php |

2. Create MySQL Table

Now, Create a MySQL Database –

Database Name – codingstatus

CREATE DATABASE codingstatus

After that create a table in the database ‘codingstatus’

CREATE TABLE `users` ( `id` int(10) NOT NULL AUTO_INCREMENT, `firstName` varchar(50) DEFAULT NOT NULL, `lastName` int(50) DEFAULT NOT NULL, `gender` int(10) DEFAULT NOT NULL, `emailAddress` int(50) DEFAULT NOT NULL, `password` int(20) DEFAULT NOT NULL );

3. Connect PHP to MySQL Database

Now, You have to connect PHP to the MySQL database with the following code

4. Create a Registration Form UI

To create the registration form UI, You have to follow the following points –

  • Create a basic HTML structure
  • Include the bootstrap5 CDN
  • Create a form with id ‘registrationForm’
  • Also, create some input fields for firstName, lastName, gender, email & submit button.
  • Include the jQuery CDN
  • Include the ajax-script.js
        

Ajax Registration Form

Male Female

5. Write ajax code for Registration

Now, We have to write ajax code to process the user Input to the PHP script. So, create a ajax-script.php and write the jquery ajax code. This code will execute when the user submits the form after filling out their registration.

To write an ajax code for registration, you have to follow the following points –

  • Apply the submit event on the form id ‘registrationForm’
  • Define the e.preventDefault to prevent the form from the reloading
  • Implement the next steps within the $.ajax()
  • define the form method post
  • define the PHP file path – php-script.php
  • also, serialize the input data using serialize() method
  • define the success to get the success response
  • display the success message in the id ‘msg’
  • After the registered successfully, make empty all the input fields.
$(document).on('submit','#registrationForm',function(e)< e.preventDefault(); $.ajax(< method:"POST", url: "php-script.php", data:$(this).serialize(), success: function(data)< $('#msg').html(data); $('#registrationForm').find('input').val('') >>); >);

6. Write PHP to Insert Registration Data

Now, We have to insert input data into the database, So, create a php-script.php file and write the php code with the MySQL query. The code of this file will run while the ajax code will be executed and sent the post request.

To insert registration data, you have to write PHP code with the following points-

  1. Include the database.php file
  2. and assign connection variable $conn to the $db
  3. Create a custom function registerUser() with two parameters $db and $userData.
  4. write a MySQLi query to insert data into the database,
  5. And then call the created function registerUser()
query($query); echo $db->error; if($execute) < echo "You are registered successfully"; >> else < echo "Wrong Confirm password"; >> else < echo "All Fields are required"; >>

7. Test Ajax Registration Form yourself

Now, You can text the ajax registration form by opening it in the web browser.

When you open the registration form will get the First Name, Last Name, gender, Email, Password & Confirm Password input fields.

After that Enter the required details and submit the form. after that, you will be registered successfully without reloading the web page.

Источник

Читайте также:  Twig render as html
Оцените статью