Sử dụng shell_exec() hoặc exec() để chạy script Python từ PHP.
Cách 1: Chạy script có shebang
File Python (test.py) cần dòng shebang đầu tiên:
#!/usr/bin/env python3
PHP:
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
Cách 2: Chỉ định interpreter trong lệnh
<?php
$command = escapeshellcmd('python3 /usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
Lưu ý quan trọng
Dùng
escapeshellcmd()hoặcescapeshellarg()để bảo mật (tránh injection).Đảm bảo user chạy web server (www-data, apache) có quyền thực thi script Python.
Đường dẫn tuyệt đối an toàn hơn đường dẫn tương đối.
Xem xét
proc_open()nếu cần tương tác stdin/stdout/stderr.Với ứng dụng production, cân nhắc message queue (RabbitMQ, Redis) thay vì gọi shell trực tiếp.