In PHP authorization systems, exposing a REST API allows clients to access and manipulate resources securely. Here's a simple example of how to create a REST API in PHP that handles user authentication and returns JSON responses.
<?php
header('Content-Type: application/json');
// Sample user data for authentication
$users = [
['username' => 'user1', 'password' => 'pass1'],
['username' => 'user2', 'password' => 'pass2'],
];
// Function to authenticate user
function authenticate($username, $password) {
global $users;
foreach ($users as $user) {
if ($user['username'] === $username && $user['password'] === $password) {
return true;
}
}
return false;
}
// Handle incoming requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$requestData = json_decode(file_get_contents('php://input'), true);
$username = $requestData['username'];
$password = $requestData['password'];
if (authenticate($username, $password)) {
echo json_encode(['message' => 'Authentication successful']);
} else {
echo json_encode(['message' => 'Authentication failed'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
} else {
echo json_encode(['message' => 'Invalid request method']);
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?