Building AI-Powered Apps in PHP — A Step-by-Step Guide

Published 2026-03-18 · Wingman Protocol

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:

This foundation enables you to build powerful AI applications with PHP while maintaining reliability and performance.

Tools We Recommend

We have tested these tools ourselves. Here are our top picks for this topic.

📚
Top AI & Machine Learning Books

Hands-On Machine Learning, Deep Learning with Python, and AI Engineering are the books that actually teach you to build things.

Browse AI Books →
DigitalOcean GPU Droplets — $200 Free Credit

Run ML models on GPU-powered instances. Perfect for fine-tuning and inference without breaking the bank.

Get $200 Free Credit →
🌐
Hostinger VPS — From $4.99/mo with Free Domain

Best value cloud hosting with LiteSpeed servers, free SSL, and 24/7 support. Great for side projects and small businesses.

Get 80% Off Hosting →

Some links above are affiliate links. We may earn a small commission at no extra cost to you.

Join 500+ developers. Get weekly API tutorials + a free starter guide.

Practical tips on AI APIs, automation, and building with LLMs — delivered every week.

No spam. Unsubscribe anytime.

Related Services

AI Chat API

From $0.05 / 1K tokens

OpenAI-compatible endpoint. Local and cloud models. Drop-in replacement for any OpenAI SDK.

⚡ Get 5 free AI guides + weekly insights

Recommended Read
Top AI & Machine Learning Books

Hands-On Machine Learning, Deep Learning with Python, and AI Engineering are the books that actually teach you to build things.

View on Amazon →
Get started →

SEO Audits

From $10 / audit

Automated technical SEO analysis. Core Web Vitals, on-page optimization, and competitive insights.

Learn more →

Content Pipeline

From $5 / piece

Blog posts, newsletters, and social media packs generated and published automatically.

Learn more →
LIMITED OFFER

Get 100 Free API Calls

Sign up now and get 100 free API calls. SEO audits, AI chat, copywriting — all included.

Try Free DemoSee Pricing

You Might Also Like

Get free weekly AI insights delivered to your inbox