Home Backend Development PHP Problem How to implement gesture login in php

How to implement gesture login in php

Apr 05, 2023 am 10:29 AM

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='用户信息表';
Copy after login

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 id="gesture" style="border: 1px solid #ccc;"></canvas>
Copy after login

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);
Copy after login

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 {
  // 登录失败
}
Copy after login

5. Complete implementation code

HTML code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Gesture Login</title>
  <style type="text/css">
    #gesture {
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <canvas id="gesture"></canvas>
  <script type="text/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;
      gestureLogin(path);
    }, false);
    // 后端接口
    var url = '/gesture/login.php';
    function gestureLogin(gesturePath) {
      var xhr = new XMLHttpRequest();
      var formData = new FormData();
      formData.append('account', 'xxx'); // 用户账号
      formData.append('gesturePath', gesturePath); // 手势路径
      xhr.open('POST', url);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status == 200) {
            var response = JSON.parse(xhr.responseText);
            if (response.code == 0) {
              alert('登录成功');
            } else {
              alert('登录失败:' + response.message);
            }
          } else {
            alert('网络错误');
          }
        }
      };
      xhr.send(formData);
    }
  </script>
</body>
</html>
Copy after login

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);
?>
Copy after login

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 of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the best practices for deduplication of PHP arrays What are the best practices for deduplication of PHP arrays Mar 03, 2025 pm 04:41 PM

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

Does PHP array deduplication need to be considered for performance losses? Does PHP array deduplication need to be considered for performance losses? Mar 03, 2025 pm 04:47 PM

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

Can PHP array deduplication take advantage of key name uniqueness? Can PHP array deduplication take advantage of key name uniqueness? Mar 03, 2025 pm 04:51 PM

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

What are the optimization techniques for deduplication of PHP arrays What are the optimization techniques for deduplication of PHP arrays Mar 03, 2025 pm 04:50 PM

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

See all articles