Table of Contents
User Authentication
User Authentication
Objective: Implement user authentication using PHP and AJAX to check if a username and password are valid.
Database Configuration (config.php):
<?php
// config.php - Database configuration
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
HTML (login.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Authentication Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="authentication-script.js"></script>
</head>
<body>
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="button" onclick="authenticateUser()">Login</button>
<p id="login-status"></p>
</form>
</body>
</html>
PHP (authenticate-user.php):
<?php
// authenticate-user.php - User authentication
include("config.php");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Validate user credentials (dummy validation for demonstration)
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = $conn->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
authenticateUserJavaScript 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.