How can one effectively implement authentication, including API keys and user credentials, in a PHP API?

To effectively implement authentication in a PHP API, you can use a combination of API keys and user credentials. API keys can be used to authenticate requests from trusted clients, while user credentials can be used for user-specific actions. You can verify API keys and user credentials against a database or an external authentication service to ensure the validity of the requests.

// Check API key
$apiKey = $_GET['api_key'];
$validApiKey = 'your_api_key_here';

if($apiKey !== $validApiKey){
    http_response_code(401);
    echo json_encode(array("message" => "Invalid API key"));
    exit();
}

// Check user credentials
$username = $_POST['username'];
$password = $_POST['password'];
$validUsername = 'admin';
$validPassword = 'password';

if($username !== $validUsername || $password !== $validPassword){
    http_response_code(401);
    echo json_encode(array("message" => "Invalid username or password"));
    exit();
}

// Proceed with API functionality