Jinsi ya Kutengeneza API Authentication kwa PHP
Code Sample:
<?php
// API key ya mfano
define('API_KEY', '123456789abcdef');
// Angalia header ya API key
$headers = getallheaders();
if (!isset($headers['Authorization'])) {
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing']);
exit;
}
// Pata key kutoka header
$apiKey = trim(str_replace('Bearer ', '', $headers['Authorization']));
// Thibitisha API key
if ($apiKey !== API_KEY) {
http_response_code(403);
echo json_encode(['error' => 'Invalid API key']);
exit;
}
// Ikiwa key sahihi, toa response
$data = [
'status' => 'success',
'message' => 'Umefanikiwa kupata data ya API!',
'data' => [
'user' => 'Faustine',
'role' => 'admin'
]
];
header('Content-Type: application/json');
echo json_encode($data);
?>
Mfano wa Request (cURL):
curl -H "Authorization: Bearer 123456789abcdef" https://example.com/api.php
Ufafanuzi:
Kila request lazima iwe na Authorization header yenye API key sahihi.
getallheaders() inakusanya headers zote kutoka request.
Hii ni njia rahisi ya authentication, lakini kwa production unashauriwa kutumia JWT au OAuth kwa usalama zaidi.
🔗 Links Za Kujifunza Zaidi:
🌐 Faulink Official Website:
https://www.faulink.com/
📘 Jifunze Web Design & Programming (Tutorials / Mifumo):
https://www.faulink.com/excel_mifumo.php
📲 Piga / WhatsApp kwa msaada wa haraka:
https://wa.me/255693118509