How can PHP developers effectively handle authentication and authorization when accessing external resources like a school's timetable?
To effectively handle authentication and authorization when accessing external resources like a school's timetable, PHP developers can use API keys or OAuth tokens to authenticate the requests. They can also implement role-based access control to ensure that only authorized users can access the timetable data.
// Example code snippet for handling authentication and authorization when accessing a school's timetable API
// Set API key or OAuth token for authentication
$api_key = 'your_api_key_here';
// Check if user is authorized to access timetable data
$user_role = 'student'; // Example user role
if ($user_role === 'student') {
// Make API request to fetch timetable data
$url = 'https://school-api.com/timetable';
$headers = ['Authorization: Bearer ' . $api_key];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process timetable data
$timetable = json_decode($response, true);
// Display timetable data
print_r($timetable);
} else {
echo 'Unauthorized access';
}