User Authentication
Table of Content:
User Authentication
Objective: Implement user authentication using PHP and AJAX to check if a username and password are valid.
Database Configuration (config.php):
connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
HTML (login.html):
User Authentication Example
PHP (authenticate-user.php):
query($sql); if ($result->num_rows > 0) { echo "Authentication successful"; } else { echo "Invalid username or password"; } } $conn->close(); ?>
JavaScript (authentication-script.js):
function authenticateUser() { // Using jQuery for AJAX request var username = $('#username').val(); var password = $('#password').val(); $.ajax({ url: 'authenticate-user.php', type: 'POST', data: { username: username, password: password }, success: function(response) { // Display authentication status $('#login-status').text(response); }, error: function(error) { console.log('Error:', error); } }); }
Explanation:
- The
authenticateUser
JavaScript function is triggered when the "Login" button is clicked. - It retrieves the entered username and password, and sends an AJAX request to
authenticate-user.php
. - The PHP file validates the user credentials against a database (dummy validation for demonstration).
- The PHP file returns an authentication status, and the JavaScript function updates the login status on the page without a full page reload.
This example showcases how PHP can be used to authenticate users, and AJAX enhances the login experience by providing real-time feedback without reloading the entire page. In a real-world scenario, you would use secure password hashing and implement additional security measures for user authentication.