How can PHP developers implement an API to allow external websites to access and display content without compromising security?
To implement an API for external websites to access and display content securely, PHP developers can use API keys for authentication and authorization. By requiring a valid API key in each request, developers can control access to the API and track usage. Additionally, developers can implement rate limiting to prevent abuse and ensure fair usage of the API.
<?php
// Check if the API key is provided in the request
if(!isset($_GET['api_key']) || $_GET['api_key'] !== 'YOUR_API_KEY') {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'Unauthorized']);
exit;
}
// Implement your API logic here