FAUSTINE MWOYA November 18, 2025

Jinsi ya Kutengeneza API Authentication kwa PHP

Pata mifumo zaidi kupitia faulink.com
API Authentication ni muhimu kuhakikisha kwamba requests zinatoka kwa watumiaji au applications halali tu. Njia rahisi na ya kawaida ni kutumia API keys au JWT (JSON Web Tokens). Hapa tutaangalia mfano wa msingi wa API key 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
Share this post
Previous Next

Comments

0
No comments yet. Be the first to comment.

Continue Reading

Subscribe

Get new updates

Jiunge upokee posts mpya, tutorials, na updates za mifumo moja kwa moja kwenye email yako.

Chat na Faulink