Building AI-Powered Apps in PHP — A Step-by-Step Guide
This tutorial walks you through creating AI-powered applications using PHP and HTTP clients. We'll cover installation, authentication, and practical examples including chat completions and SEO audits.
Installation and Setup Start by installing Guzzle HTTP client via Composer: composer require guzzlehttp/guzzle
Create a configuration file to store your API credentials:// config.php
define('API_BASE_URL', 'https://api.wingmanprotocol.com/v1');
define('API_KEY', 'your_api_key_here');
Authentication
Most AI APIs require authentication via API key in the request header. Here's a helper function:
function createApiClient() {
return new \GuzzleHttp\Client([
'base_uri' => API_BASE_URL,
'headers' => [
'Authorization' => 'Bearer ' . API_KEY,
'Content-Type' => 'application/json',
]
]);
}
Chat Completions Example
Here's a complete working example for chat completions:
<?php
require_once 'vendor/autoload.php';
require_once 'config.php';
function generateChatResponse($messages) {
$client = createApiClient();
try {
$response = $client->post('/chat/completions', [
'json' => [
'model' => 'gpt-4',
'messages' => $messages,
'max_tokens' => 2000,
]
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
error_log("Chat API error: " . $e->getMessage());
return null;
}
}
// Usage
$messages = [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Explain quantum computing simply.'],
];
$result = generateChatResponse($messages);
echo $result['choices'][0]['message']['content'];
SEO Audit Example
Here's a practical SEO audit implementation:
function seoAudit($url) {
$client = createApiClient();
try {
$response = $client->post('/seo/audit', [
'json' => [
'target_url' => $url,
'analysis_depth' => 'comprehensive',
'include_recommendations' => true,
]
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
error_log("SEO API error: " . $e->getMessage());
return null;
}
}
// Usage
echo "SEO Score: " . $audit['score'] . "\n";
echo "Recommendations: \n";
foreach ($audit['recommendations'] as $rec) {
echo "- " . $rec['title'] . "\n";
}
Error Handling
Implement robust error handling for API calls:
function callApi($endpoint, $data = []) {
$client = createApiClient();
try {
$response = $client->post($endpoint, [
'json' => $data,
'timeout' => 30,
]);
return [
'success' => true,
'data' => json_decode($response->getBody(), true),
];
} catch (\GuzzleHttp\Exception\ServerException $e) {
return [
'success' => false,
'error' => 'Server error: ' . $e->getResponse()->getBody(),
];
} catch (\GuzzleHttp\Exception\ClientException $e) {
return [
'success' => false,
'error' => 'Client error: ' . $e->getResponse()->getBody(),
];
} catch (\Exception $e) {
return [
'success' => false,
'error' => 'Request failed: ' . $e->getMessage(),
];
}
}
Rate Limits and Best Practices
Monitor API usage and implement rate limiting:
function rateLimitedRequest($endpoint, $data = []) {
static $lastRequestTime = 0;
$minInterval = 1; // seconds between requests
$currentTime = microtime(true);
$timeSinceLast = $currentTime - $lastRequestTime;
if ($timeSinceLast < $minInterval) {
usleep(($minInterval - $timeSinceLast) * 1000000);
}
$lastRequestTime = microtime(true);
return callApi($endpoint, $data);
}
Additional best practices:
- Cache responses when possible to reduce API calls
- Use environment variables for sensitive credentials
- Implement exponential backoff for retries
- Monitor API usage quotas
- Handle timeouts gracefully