search
HomeBackend DevelopmentPHP ProblemHow to implement gesture login in php

Gesture login is already very common on mobile devices. Users only need to slide the specified gesture on the screen to log in to the system, without having to enter cumbersome account passwords. This article will introduce how to implement gesture login using PHP.

1. Preparation

First of all, some basic knowledge is required. PHP has become one of the most popular server-side scripting languages ​​in the world, with a wide range of applications and a large developer community. If you don’t know much about PHP yet, it is recommended to learn some basic PHP knowledge first.

Secondly, some front-end knowledge is required. Gesture login is implemented based on front-end technology, involving HTML, CSS, JavaScript and other technologies, so it requires a certain understanding of the front-end.

Finally, some algorithm knowledge is required. Gesture login involves how to recognize the pattern drawn by the user, so it requires some algorithm knowledge. Here are some related algorithms recommended: $1.Leap Motion$, $2.Golden Section Search$, $3.Longest Common Subsequence(LCS)$.

2. Implementation steps

1. Build a PHP environment

To build a PHP running environment, you can use WAMP, XAMPP, MAMP and other software, or you can configure Apache Nginx MySQL PHP operating environment.

2. Design database

Design a user table to save user account, password, gesture and other information. The table structure can be as follows:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account` varchar(20) NOT NULL COMMENT '用户名或注册邮箱',
  `password` varchar(36) NOT NULL COMMENT '登录密码',
  `gesture` text COMMENT '手势锁',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户信息表';

3. Front-end implementation of gesture drawing

Use HTML, CSS and JavaScript to implement the front-end page, which is used to display gesture patterns, process user drawing gestures and other operations.

1) Create a canvas to draw gestures.

<canvas></canvas>

2) Implement gesture drawing through JavaScript

var canvas = document.getElementById('gesture');
var context = canvas.getContext('2d');
var start = false;
var path = '';
canvas.addEventListener('touchstart', function(event) {
  start = true;
  path = '';
  var touch = event.touches[0];
  var x = touch.pageX - canvas.offsetLeft;
  var y = touch.pageY - canvas.offsetTop;
  context.beginPath();
  context.moveTo(x, y);
}, false);
canvas.addEventListener('touchmove', function(event) {
  if (start) {
    var touch = event.touches[0];
    var x = touch.pageX - canvas.offsetLeft;
    var y = touch.pageY - canvas.offsetTop;
    path += x + ',' + y + ';';
    context.lineTo(x, y);
    context.stroke();
  }
}, false);
canvas.addEventListener('touchend', function(event) {
  start = false;
  console.log('gesture path:', path);
}, false);

4. Back-end implementation of gesture recognition

The back-end receives the gesture data from the front-end and recognizes it to determine whether the gesture is correct.

// 读取用户的手势锁
$sql = 'SELECT gesture FROM users WHERE account = \''.$account.'\'';
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$gesture = $row['gesture'];
// 计算用户绘制的手势锁的MD5值
$md5 = md5($gesturePath);
if ($md5 == $gesture) {
  // 登录成功
} else {
  // 登录失败
}

5. Complete implementation code

HTML code:

nbsp;html>


  
  Gesture Login
  


  <canvas></canvas>
  <script>
    var canvas = document.getElementById(&#39;gesture&#39;);
    var context = canvas.getContext(&#39;2d&#39;);
    var start = false;
    var path = &#39;&#39;;
    canvas.addEventListener(&#39;touchstart&#39;, function(event) {
      start = true;
      path = &#39;&#39;;
      var touch = event.touches[0];
      var x = touch.pageX - canvas.offsetLeft;
      var y = touch.pageY - canvas.offsetTop;
      context.beginPath();
      context.moveTo(x, y);
    }, false);
    canvas.addEventListener(&#39;touchmove&#39;, function(event) {
      if (start) {
        var touch = event.touches[0];
        var x = touch.pageX - canvas.offsetLeft;
        var y = touch.pageY - canvas.offsetTop;
        path += x + &#39;,&#39; + y + &#39;;&#39;;
        context.lineTo(x, y);
        context.stroke();
      }
    }, false);
    canvas.addEventListener(&#39;touchend&#39;, function(event) {
      start = false;
      gestureLogin(path);
    }, false);
    // 后端接口
    var url = &#39;/gesture/login.php&#39;;
    function gestureLogin(gesturePath) {
      var xhr = new XMLHttpRequest();
      var formData = new FormData();
      formData.append(&#39;account&#39;, &#39;xxx&#39;); // 用户账号
      formData.append(&#39;gesturePath&#39;, gesturePath); // 手势路径
      xhr.open(&#39;POST&#39;, url);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status == 200) {
            var response = JSON.parse(xhr.responseText);
            if (response.code == 0) {
              alert(&#39;登录成功&#39;);
            } else {
              alert(&#39;登录失败:&#39; + response.message);
            }
          } else {
            alert(&#39;网络错误&#39;);
          }
        }
      };
      xhr.send(formData);
    }
  </script>

PHP code:

<?php // 连接数据库
$con = mysqli_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;root&#39;, &#39;test&#39;) or die(&#39;连接失败&#39;);
mysqli_set_charset($con, &#39;utf8mb4&#39;);
// 判断是否POST请求
if ($_SERVER[&#39;REQUEST_METHOD&#39;] == &#39;POST&#39;) {
  // 读取请求参数
  $account = mysqli_real_escape_string($con, $_POST[&#39;account&#39;]);
  $gesturePath = mysqli_real_escape_string($con, $_POST[&#39;gesturePath&#39;]);
  // 读取用户的手势锁
  $sql = &#39;SELECT gesture FROM users WHERE account = \&#39;&#39;.$account.&#39;\&#39;&#39;;
  $result = mysqli_query($con, $sql);
  if ($result) {
    $row = mysqli_fetch_assoc($result);
    $gesture = $row[&#39;gesture&#39;];
    // 计算用户绘制的手势锁的MD5值
    $md5 = md5($gesturePath);
    if ($md5 == $gesture) {
      // 登录成功
      $response = array(
        &#39;code&#39; => 0,
        'message' => '登录成功'
      );
    } else {
      // 登录失败
      $response = array(
        'code' => -1,
        'message' => '手势不正确'
      );
    }
  } else {
    // 用户不存在
    $response = array(
      'code' => -1,
      'message' => '用户不存在'
    );
  }
  // 返回结果
  header('Content-Type: application/json;charset=utf-8');
  echo json_encode($response);
} else {
  // 非POST请求
  http_response_code(404);
}
// 关闭数据库连接
mysqli_close($con);
?>

3. Summary

This article introduces Specific steps to implement gesture login using PHP. Through the cooperation of the front and back ends, users can use gestures instead of entering cumbersome account passwords when logging in to the system on mobile devices, which improves user experience and security. Although gesture login is relatively simple to implement, there are still many issues that need to be considered in the actual application of the technology, such as security, ease of use, performance, etc., which need to be continuously optimized and improved in actual applications.

The above is the detailed content of How to implement gesture login in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.