Làm cách nào để xác thực mã PHP?

Tóm lược. trong hướng dẫn này, bạn sẽ tìm hiểu về xác thực biểu mẫu PHP, cách xác thực dữ liệu biểu mẫu và cách hiển thị thông báo lỗi nếu thông tin nhập của người dùng không hợp lệ

Giới thiệu về xác thực biểu mẫu PHP

Khi xử lý một biểu mẫu, điều quan trọng là phải xác thực đầu vào của người dùng để đảm bảo rằng dữ liệu ở định dạng hợp lệ

Có hai loại xác thực. phía máy khách và phía máy chủ

Xác thực phía máy khách được thực hiện trong trình duyệt web của người dùng. Để xác thực dữ liệu ở phía máy khách, bạn có thể sử dụng xác thực HTML5 hoặc JavaScript. Xác thực phía máy khách nhằm mục đích hỗ trợ người dùng hợp pháp nhập dữ liệu ở định dạng hợp lệ trước khi gửi tới máy chủ

Tuy nhiên, xác thực phía máy khách không ngăn người dùng độc hại gửi dữ liệu có khả năng khai thác ứng dụng

Xác thực phía máy chủ xác thực dữ liệu trong máy chủ web bằng PHP. Để xác thực dữ liệu trong PHP, bạn có thể sử dụng hàm

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
0 và

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
1

Ví dụ xác thực biểu mẫu PHP

Chúng tôi sẽ xây dựng một biểu mẫu đăng ký email bao gồm tính năng xác thực. Biểu mẫu có các thành phần đầu vào tên và email và nút gửi

Làm cách nào để xác thực mã PHP?
Làm cách nào để xác thực mã PHP?

Nếu bạn không nhập tên và/hoặc email và nhấp vào nút đăng ký, biểu mẫu sẽ hiển thị thông báo lỗi. Ngoài ra, nếu bạn nhập địa chỉ email không hợp lệ, biểu mẫu sẽ hiển thị một thông báo lỗi khác

Lưu ý rằng chúng tôi không sử dụng xác thực phía máy khách cho biểu mẫu này để giúp kiểm tra dễ dàng hơn. Trong thực tế, bạn cũng nên sử dụng xác thực phía máy khách

Sắp xếp thư mục và tập tin

Đầu tiên, tạo cấu trúc tệp và thư mục như sau

. ├── css │ └── style.css ├── inc │ ├── get.php │ ├── post.php │ ├── header.php │ ├── footer.php │ └── .htaccess └── index.php

Code language: plaintext (plaintext)

Bảng sau đây mô tả mục đích của từng tệp

FileDirectoryDescriptionindex. php. Chứa logic chính của formheader. phpincChứa codefooter tiêu đề. phpincChứa bộ mã chân trang. phpincChứa formpost đăng ký email. phpincChứa mã để xử lý kiểu gửi biểu mẫu. csscssChứa mã CSS

tiêu đề. php

Sau đây hiển thị tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
2

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)

Tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
2 liên kết với tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
4 trong thư mục

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
5

cuối trang. php

Và tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
6 chỉ chứa các thẻ kèm theo tương ứng với các thẻ mở trong tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
2

main> body> html>

Code language: HTML, XML (xml)

mục lục. php

Tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
8 chứa logic chính của biểu mẫu

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)

Cách thức hoạt động của

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
8

Đầu tiên, tải mã từ cả hai tệp

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
2 và

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
6 bằng cách sử dụng cấu trúc

main> body> html>

Code language: HTML, XML (xml)
2 ở đầu và cuối tệp để tạo đầu trang và chân trang

Thứ hai, xác định mảng

main> body> html>

Code language: HTML, XML (xml)
3 để lưu trữ các thông báo lỗi và mảng

main> body> html>

Code language: HTML, XML (xml)
4 để lưu trữ các giá trị biểu mẫu đã nhập. Nếu một phần tử đầu vào có dữ liệu không hợp lệ, thì

html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> <title>Subscribetitle> head> <body> <main>

Code language: HTML, XML (xml)
8 sẽ hiển thị giá trị đã nhập được lưu trữ trong

main> body> html>

Code language: HTML, XML (xml)
4

Thứ ba, hiển thị biểu mẫu nếu phương thức yêu cầu HTTP là GET bằng cách tải get. tập tin php. Sau khi bạn vào

Cuối cùng, tải mã trong

main> body> html>

Code language: HTML, XML (xml)
7 để xử lý việc gửi biểu mẫu nếu phương thức yêu cầu HTTP là POST. Nếu biểu mẫu có bất kỳ lỗi nào, thì

main> body> html>

Code language: HTML, XML (xml)
3 sẽ không trống. Trong trường hợp này, hãy hiển thị lại biểu mẫu với các thông báo lỗi được lưu trong mảng

main> body> html>

Code language: HTML, XML (xml)
3 và các giá trị đã nhập được lưu trong mảng

main> body> html>

Code language: HTML, XML (xml)
4

được. php

Tệp

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)
1 chứa biểu mẫu

<form action="" method="post"> <header> <h1>Get FREE Updatesh1> <p>Join us for FREE to get email updates!p> header> <div> <label for="name">Name:label> <input type="text" name="name" id="name" placeholder="Full Name" value="" class=""> <small> echo $errors['name'] ?? '' ?>small> div> <div> <label for="name">Email:label> <input type="text" name="email" id="email" placeholder="Email Address" value="" class=""> <small> echo $errors['email'] ?? '' ?>small> div> <button type="submit">Subscribebutton> form>

Code language: HTML, XML (xml)

Cách thức hoạt động của

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)
1

  • Đầu tiên, hãy điền các phần tử đầu vào tên và email bằng các giá trị đã nhập được lưu trữ trong mảng

    main> body> html>

    Code language: HTML, XML (xml)
    4 chỉ khi các giá trị này tồn tại
  • Thứ hai, hiển thị các thông báo lỗi được lưu trữ trong mảng

    main> body> html>

    Code language: HTML, XML (xml)
    3 nếu chúng tồn tại

bưu kiện. php

Phần sau hiển thị mã của tệp

main> body> html>

Code language: HTML, XML (xml)
7.

main> body> html>

Code language: HTML, XML (xml)
7 xác thực dữ liệu biểu mẫu bằng cách sử dụng các hàm

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)
7 và

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)
8

const NAME_REQUIRED = 'Please enter your name'; const EMAIL_REQUIRED = 'Please enter your email'; const EMAIL_INVALID = 'Please enter a valid email'; // sanitize and validate name $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $inputs['name'] = $name; if ($name) { $name = trim($name); if ($name === '') { $errors['name'] = NAME_REQUIRED; } } else { $errors['name'] = NAME_REQUIRED; } // sanitize & validate email $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $inputs['email'] = $email; if ($email) { // validate email $email = filter_var($email, FILTER_VALIDATE_EMAIL); if ($email === false) { $errors['email'] = EMAIL_INVALID; } } else { $errors['email'] = EMAIL_REQUIRED; } ?> if (count($errors) === 0) : ?> <section> <h2> Thanks echo htmlspecialchars($name) ?> for your subscription! h2> <p>Please follow the steps below to complete your subscription:p> <ol> <li>Check your email ( echo htmlspecialchars($email) ?>) - Find the message sent from [email protected]li> <li>Click to confirm - Click on the link in the email to confirm your subscription.li> ol> section> endif ?>

Code language: HTML, XML (xml)

Làm thế nào nó hoạt động

Đầu tiên, xác định một số hằng số để lưu trữ các thông báo lỗi. Trong một ứng dụng trong thế giới thực, bạn có thể lưu trữ tất cả các tin nhắn trong một tệp riêng biệt

const NAME_REQUIRED = 'Please enter your name'; const EMAIL_REQUIRED = 'Please enter your email'; const EMAIL_INVALID = 'Please enter a valid email';

Code language: JavaScript (javascript)

Thứ hai, làm sạch và xác thực tên bằng hàm filter_input(). Nếu tên trống, hãy thêm thông báo lỗi vào mảng

main> body> html>

Code language: HTML, XML (xml)
3

// sanitize and validate name $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $inputs['name'] = $name; if ($name) { $name = trim($name); if ($name === '') { $errors['name'] = NAME_REQUIRED; } } else { $errors['name'] = NAME_REQUIRED; }

Code language: PHP (php)

Thứ ba, làm sạch và xác thực email bằng các chức năng

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)
7 và

require __DIR__ . '/inc/header.php'; $errors = []; $inputs = []; $request_method = strtoupper($_SERVER['REQUEST_METHOD']); if ($request_method === 'GET') { // show the form require __DIR__ . '/inc/get.php'; } elseif ($request_method === 'POST') { // handle the form submission require __DIR__ . '/inc/post.php'; // show the form if the error exists if (count($errors) > 0) { require __DIR__ . '/inc/get.php'; } } require __DIR__ . '/inc/footer.php';

Code language: HTML, XML (xml)
8. Nếu email trống hoặc không hợp lệ, hãy thêm thông báo lỗi tương ứng vào mảng

main> body> html>

Code language: HTML, XML (xml)
3

// sanitize & validate email $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $inputs['email'] = $email; if ($email) { // validate email $email = filter_var($email, FILTER_VALIDATE_EMAIL); if ($email === false) { $errors['email'] = EMAIL_INVALID; } } else { $errors['email'] = EMAIL_REQUIRED; }

Code language: PHP (php)

Cuối cùng nếu form không có lỗi thì hiện thông báo xác nhận

if (count($errors) === 0) : ?> <section> <h2> Thanks echo htmlspecialchars($name) ?> for your subscription! h2> <p>Please follow the steps below to complete your subscription:p> <ol> <li>Check your email ( echo htmlspecialchars($email) ?>) - Find the message sent from [email protected]li> <li>Click to confirm - Click on the link in the email to confirm your subscription.li> ol> section> endif ?>

Code language: HTML, XML (xml)

Để hoàn thành biểu mẫu, bạn có thể lưu dữ liệu liên hệ vào cơ sở dữ liệu hoặc gọi API của dịch vụ tiếp thị qua email để thêm liên hệ vào danh sách của bạn

Xác thực có thể được thực hiện trong PHP không?

Xác thực biểu mẫu là quy trình cần thiết trước khi dữ liệu nhập vào biểu mẫu được gửi tới cơ sở dữ liệu . Điều này được thực hiện để tránh các lỗi không cần thiết. Trong xác thực Biểu mẫu PHP, tập lệnh kiểm tra dữ liệu trong các trường tương ứng dựa trên các quy tắc do nhà phát triển đặt và trả về lỗi nếu không đáp ứng yêu cầu.

Làm cách nào để xác thực đầu vào trong PHP?

PHP có hàm filter_var() để xác thực các biến . Chúng tôi có thể đặt tham số thứ hai của nó thành các giá trị khác nhau và sử dụng nó để xác thực email, URL, số nguyên, booleans, v.v. Hàm này trả về false khi lỗi hoặc đầu vào không hợp lệ. Chúng tôi chỉ có thể xác thực email bằng hàm filter_var() và cờ FILTER_VALIDATE_EMAIL.

Xác thực trong PHP nghĩa là gì?

Xác thực có nghĩa là kiểm tra thông tin đầu vào do người dùng gửi . Có hai loại xác thực có sẵn trong PHP. Chúng như sau - Xác thực phía máy khách - Xác thực được thực hiện trên các trình duyệt web của máy khách.

Làm cách nào để xác thực một số trong PHP?

Hàm is_numeric() kiểm tra xem một biến là số hay chuỗi số. Hàm này trả về true (1) nếu biến là số hoặc chuỗi số, ngược lại trả về false/không có gì.