How can a webservice be secured using username, password, and token in PHP?

To secure a webservice using username, password, and token in PHP, you can create a login system where users provide their credentials (username and password) to obtain a token. This token can then be used in subsequent requests to authenticate the user.

<?php

// Check username and password
if ($_POST['username'] == 'example_user' && $_POST['password'] == 'example_password') {
    // Generate a token
    $token = bin2hex(random_bytes(16));
    
    // Store the token in a session or database
    $_SESSION['token'] = $token;
    
    // Return the token to the user
    echo json_encode(['token' => $token]);
} else {
    // Return an error message
    echo json_encode(['error' => 'Invalid username or password']);
}

?>