📖 Documentation: Contributing · Security · Changelog · Funding
php-chatbot is a modern, framework-agnostic PHP package for integrating an AI-powered chat popup into any web application. It features out-of-the-box support for Laravel and Symfony, a flexible model abstraction for using OpenAI, Anthropic, xAI, Google Gemini, Meta, and more, and is designed for easy customization and extension. Build your own UI or use the provided minimal frontend as a starting point. High test coverage, static analysis, and coding standards are included.
- Plug-and-play chat popup UI (minimal frontend dependencies)
- Laravel & Symfony support via adapters/service providers
- AI model abstraction via contracts (swap models easily)
- Customizable prompts, tone, language, and scope
- Emoji and multi-script support (Cyrillic, Greek, Armenian, Asian, etc.)
- Security safeguards against abuse
- High test coverage (Pest)
- Static analysis (phpstan) & coding standards (phpcs, Symfony style)
Comprehensive documentation and guides are available in our GitHub Wiki:
- Installation Guide - Step-by-step installation for all environments
- Quick Start Guide - Get up and running in minutes
- Configuration - Complete configuration reference
- Framework Integration - Laravel, Symfony, and plain PHP setup
- Frontend Integration - React, Vue, Angular components and examples
- AI Models - Provider comparison and configuration
- Examples - Real-world implementations and use cases
- Best Practices - Production deployment and security guidelines
- Security & Filtering - Content filtering and abuse prevention
- API Reference - Complete API documentation
- Troubleshooting - Common issues and solutions
- Contributing - How to contribute to the project
- FAQ - Frequently asked questions
💡 Tip: The wiki contains production-ready examples, troubleshooting guides, and comprehensive API documentation that goes beyond this README.
Provider | Example Models / Notes | API Key Required | Local/Remote |
---|---|---|---|
OpenAI | gpt-4.1, gpt-4o, gpt-4o-mini, gpt-3.5-turbo, etc. | Yes | Remote |
Anthropic | Claude 3 Sonnet, 3.7, 4, etc. | Yes | Remote |
xAI | Grok-1, Grok-1.5, etc. | Yes | Remote |
Gemini 1.5 Pro, Gemini 1.5 Flash, etc. | Yes | Remote | |
Meta | Llama 3 (8B, 70B), etc. | Yes | Remote |
Ollama | llama2, mistral, phi3, and any local Ollama model | No (local) / Opt | Local/Remote |
Free model | Simple fallback, no API key required | No | Local |
composer require rumenx/php-chatbot
- Package auto-discovers the service provider.
- Publish config:
php artisan vendor:publish --provider="Rumenx\\PhpChatbot\\Adapters\\Laravel\\PhpChatbotServiceProvider"
- Register the bundle in your
bundles.php
. - Publish config:
php bin/console chatbot:publish-config
- Add the chat popup to your layout (see
/resources/views
for examples). - Configure your preferred AI model and prompts in the config file (
src/Config/phpchatbot.php
). - Optionally, customize the frontend (CSS/JS) in
/resources
.
Never hardcode API keys or secrets in your codebase.
- Use environment variables (e.g.
.env
file) or your infrastructure's secret management. - The config file will check for environment variables (e.g.
OPENAI_API_KEY
,ANTHROPIC_API_KEY
, etc.) first. - See
.env.example
for reference.
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;
$config = require 'src/Config/phpchatbot.php';
$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);
$reply = $chatbot->ask('Hello!');
echo $reply;
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
XAI_API_KEY=...
- Endpoint:
/php-chatbot/message
- Request:
{ "message": "Hello" }
- Response:
{ "reply": "Hi! How can I help you?" }
// src/Controller/ChatbotController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;
class ChatbotController extends AbstractController
{
public function message(Request $request): JsonResponse
{
$config = require $this->getParameter('kernel.project_dir').'/src/Config/phpchatbot.php';
$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);
$input = $request->toArray()['message'] ?? '';
$reply = $chatbot->ask($input);
return $this->json(['reply' => $reply]);
}
}
composer test
composer test
# or for coverage
./vendor/bin/pest --coverage --min=90
composer analyze
composer style
- Input validation and abuse prevention built-in.
- Rate limiting and content filtering available via config.
You can implement rate limiting and abuse prevention in your backend. For Laravel, use built-in middleware:
// routes/web.php
Route::post('/php-chatbot/message', function (Request $request) {
// ...existing code...
})->middleware('throttle:10,1'); // 10 requests per minute per IP
For plain PHP, you can use a simple session or IP-based limiter, or integrate a package like malkusch/lock
or Redis.
You can use the provided chat popup as a plain HTML/JS snippet, or integrate a modern component for Vue, React, or Angular:
- Vue:
resources/js/components/PhpChatbotVue.vue
- React:
resources/js/components/PhpChatbotReact.jsx
- Angular:
resources/js/components/PhpChatbotAngular.html
(with TypeScript logic)
- Copy the component into your app's source tree.
- Import and register it in your app (see your framework's docs).
- Customize the backend endpoint (
/php-chatbot/message
) as needed. - Build your assets (e.g. with Vite, Webpack, or your framework's CLI).
// main.js
import PhpChatbotVue from './components/PhpChatbotVue.vue';
app.component('PhpChatbotVue', PhpChatbotVue);
import PhpChatbotReact from './components/PhpChatbotReact.jsx';
<PhpChatbotReact />
- Copy the HTML, TypeScript, and CSS into your Angular component files.
- Register and use
<php-chatbot-angular></php-chatbot-angular>
in your template.
- You can style or extend the components as needed.
- You may add your own framework component in a similar way.
- The backend endpoint is framework-agnostic; you can point it to any PHP route/controller.
A modern TypeScript React chatbot component is provided as an example in resources/js/components/PhpChatbotTs.tsx
.
How to use:
-
Copy
PhpChatbotTs.tsx
into your React app's components folder. -
Import and use it in your app:
import PhpChatbotTs from './components/PhpChatbotTs'; // ... <PhpChatbotTs />
-
Make sure your backend endpoint
/php-chatbot/message
is set up as described above. -
Style as needed (the component uses inline styles for demo purposes, but you can use your own CSS/SCSS).
This component is a minimal, framework-agnostic starting point. You are encouraged to extend or restyle it to fit your app.
To handle chat requests, add a route/controller in your backend (Laravel, Symfony, or plain PHP) that receives POST requests at /php-chatbot/message
and returns a JSON response. Example for Laravel:
// routes/web.php
use Illuminate\Http\Request;
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;
use Illuminate\Support\Facades\Log;
Route::post('/php-chatbot/message', function (Request $request) {
$config = config('phpchatbot');
$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);
$context = [
'prompt' => $config['prompt'],
'logger' => Log::getFacadeRoot(), // Optional PSR-3 logger
];
$reply = $chatbot->ask($request->input('message'), $context);
return response()->json(['reply' => $reply]);
});
For plain PHP, use:
// public/php-chatbot-message.php
require '../vendor/autoload.php';
use Rumenx\PhpChatbot\PhpChatbot;
use Rumenx\PhpChatbot\Models\ModelFactory;
$config = require '../src/Config/phpchatbot.php';
$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);
$input = json_decode(file_get_contents('php://input'), true)['message'] ?? '';
$reply = $chatbot->ask($input);
header('Content-Type: application/json');
echo json_encode(['reply' => $reply]);
The chat popup styles are written in modern SCSS for maintainability. You can find the source in resources/css/chatbot.scss
.
To compile SCSS to CSS:
-
Install Sass (if you haven't already):
npm install --save-dev sass
-
Add this script to your
package.json
:"scripts": { "scss": "sass resources/css/chatbot.scss resources/css/chatbot.css --no-source-map" }
-
Compile SCSS:
npm run scss
Or use the Sass CLI directly:
sass resources/css/chatbot.scss resources/css/chatbot.css --no-source-map
To watch for changes automatically:
sass --watch resources/css/chatbot.scss:resources/css/chatbot.css --no-source-map
Only commit the compiled
chatbot.css
for production/deployment. For more options, see Sass documentation.
The provided CSS/SCSS and view files (resources/css/
, resources/views/
) are optional and basic. They are meant as a starting point for your own implementation. You are encouraged to build your own UI and styles on top of or instead of these defaults.
Do not edit files directly in the vendor/
folder or inside the package source.
-
Copy the provided view files (e.g.
resources/views/popup.blade.php
orpopup.php
) into your own application's views directory. Update your app to use your custom view. -
Copy and modify the SCSS/CSS (
resources/css/chatbot.scss
orchatbot.css
) into your own asset pipeline. Import, extend, or replace as needed. -
For Laravel/Symfony:
-
Publish the package views/config (see the Installation section above) and edit the published files in your app, not in
vendor/
. -
Example (Laravel):
php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider" --tag=views
-
Example (Symfony):
php bin/console chatbot:publish-views
-
-
For plain PHP: Copy the view and style files to your public or template directory and reference them in your HTML.
Important: If you edit files directly in
vendor/rumenx/php-chatbot/
, your changes will be lost on the nextcomposer update
. Always override or extend in your own app.
- Treat the package's frontend as a reference implementation.
- Override or extend in your own codebase for all customizations.
- Never edit vendor files directly.
Never edit files in the vendor/
directory.
-
For Laravel: Publish the config file to your app's
config/
directory using:php artisan vendor:publish --provider="Rumenx\PhpChatbot\Adapters\Laravel\PhpChatbotServiceProvider"
Then edit
config/phpchatbot.php
in your app. This file will not be overwritten by package updates. -
For Symfony: Use the provided command to publish config to your app's config directory, then edit as needed.
-
For plain PHP or other frameworks: Use an environment variable to point to your own config file.
- Copy
src/Config/phpchatbot.php
to a safe location in your project (e.g.,config/phpchatbot.php
). - Set the environment variable in your
.env
or server config:PHPCHATBOT_CONFIG_PATH=/path/to/your/config/phpchatbot.php
- In your bootstrap or controller, load config like this:
$configPath = getenv('PHPCHATBOT_CONFIG_PATH') ?: __DIR__ . '/../vendor/rumenx/php-chatbot/src/Config/phpchatbot.php'; $config = require $configPath;
- Copy
-
Always use environment variables for secrets and API keys.
-
Never edit or commit changes to files in
vendor/
. -
Document your custom config location for your team.
Example usage in a plain PHP project:
$configPath = getenv('PHPCHATBOT_CONFIG_PATH') ?: __DIR__ . '/../vendor/rumenx/php-chatbot/src/Config/phpchatbot.php';
$config = require $configPath;
$model = ModelFactory::make($config);
$chatbot = new PhpChatbot($model, $config);
This approach ensures your configuration is safe from being overwritten during package updates and is easy to manage in any deployment environment.
- Never edit files in
vendor/
- Always copy views/styles to your own app before customizing
- Use environment variables for secrets
- Use the provided JS/TS components as a starting point, not as production code
- Keep your customizations outside the package directory for upgrade safety
Feature | Location/Example | Optional/Required |
---|---|---|
PHP Core Classes | src/ |
Required |
Laravel Adapter | src/Adapters/Laravel/ |
Optional |
Symfony Adapter | src/Adapters/Symfony/ |
Optional |
Config File | src/Config/phpchatbot.php |
Required |
Blade/PHP Views | resources/views/ |
Optional |
CSS/SCSS | resources/css/chatbot.scss /chatbot.css |
Optional |
JS/TS Components | resources/js/components/ |
Optional |
Example .env | .env.example |
Optional |
Tests | tests/ |
Optional |
The package includes a configurable chat message filtering middleware to help ensure safe, appropriate, and guideline-aligned AI responses. This middleware:
- Filters and optionally rephrases user-submitted messages before they reach the AI model.
- Appends hidden system instructions (not visible in chat history) to the AI context, enforcing safety and communication guidelines.
- All filtering rules (profanities, aggression patterns, link regex) and system instructions are fully configurable in
src/Config/phpchatbot.php
.
Example configuration:
'message_filtering' => [
'instructions' => [
'Avoid sharing external links.',
'Refrain from quoting controversial sources.',
'Use appropriate language.',
'Reject harmful or dangerous requests.',
'De-escalate potential conflicts and calm aggressive or rude users.',
],
'profanities' => ['badword1', 'badword2'],
'aggression_patterns' => ['hate', 'kill', 'stupid', 'idiot'],
'link_pattern' => '/https?:\/\/[\w\.-]+/i',
],
Example usage in your controller or chat service:
use Rumenx\PhpChatbot\Middleware\ChatMessageFilterMiddleware;
$config = require 'src/Config/phpchatbot.php';
$filterCfg = $config['message_filtering'] ?? [];
$middleware = new ChatMessageFilterMiddleware(
$filterCfg['instructions'] ?? [],
$filterCfg['profanities'] ?? [],
$filterCfg['aggression_patterns'] ?? [],
$filterCfg['link_pattern'] ?? ''
);
// Before sending to the AI model:
$filtered = $middleware->handle($userMessage, $context);
$reply = $chatbot->ask($filtered['message'], $filtered['context']);
Purpose:
- Promotes safe, respectful, and effective communication.
- Prevents misuse, abuse, and unsafe outputs.
- All rules are transparent and configurable—no hidden censorship or manipulation.
For questions, issues, or feature requests, please use the GitHub Issues page.
For security vulnerabilities, please see our Security Policy.
See CONTRIBUTING.md for guidelines on how to contribute.
This project adheres to a Code of Conduct to ensure a welcoming and inclusive environment for all contributors. See CODE_OF_CONDUCT.md for details.
If you find this project helpful, consider supporting its development. See FUNDING.md for ways to contribute.
See CHANGELOG.md for a detailed history of changes and releases.
MIT. See LICENSE.md.