API untuk mengeksekusi script Python dari PHP dengan autentikasi dasar dan manajemen parameter yang aman.
- 🛡️ Autentikasi Basic Auth
- 📦 Pemisahan kode yang rapi (MVC-like structure)
- 🔐 Validasi input parameter
- 📝 Logika bisnis terpisah
- 🐍 Support eksekusi Python 3
- 🚀 Error handling terstruktur
- 🔧 Konfigurasi terpusat
- PHP 7.4+
- Python 3.6+
- Apache/Nginx dengan mod_rewrite aktif
- Composer (opsional untuk pengembangan)
.
├── api/
│ ├── includes/
│ │ ├── Config.php # File konfigurasi
│ │ ├── Auth.php # Logika autentikasi
│ │ └── PythonRunner.php # Penangan eksekusi Python
│ └── run_python.php # Endpoint utama
├── scripts/
│ └── main.py # Contoh script Python
└── .htaccess # Konfigurasi URL rewriting
- Clone repositori:
git clone https://github.com/MarioAPasama/php-run-python.git
cd php-python-api
- Atur permission:
chmod 755 api/includes/
chmod 644 api/includes/*
chmod 755 scripts/
- Konfigurasi awal:
cp api/includes/Config.php.example api/includes/Config.php
Konfigurasi Edit api/includes/Config.php:
class Config {
const PYTHON_PATH = '/usr/bin/python3'; // Path ke Python 3
const VALID_USERNAME = 'admin'; // Username untuk Basic Auth
const VALID_PASSWORD = 'strongpassword';// Password untuk Basic Auth
const MAX_PARAMS = 5; // Batas maksimal parameter
const ALLOWED_CHARS = '/^[a-z0-9\-_ ]+$/i'; // Pola karakter yang diizinkan
}Penggunaan API Request Contoh
curl -X POST \
-u admin:strongpassword \
-F "params[]=hello" \
-F "params[]=world" \
http://localhost/api/python
Format Response Sukses
{
"success": true,
"output": "{\"result\": \"HELLO WORLD\"}",
"error": null
}
Format Response Error
{
"success": false,
"output": null,
"error": {
"code": 403,
"message": "Invalid credentials"
}
}