Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

รันโปรแกรม Python จาก PHP ด้วย shell_exec

สามารถเรียกใช้สคริปต์ Python จาก PHP ได้โดยใช้ฟังก์ชัน shell_exec() ซึ่งจะรันคำสั่งผ่าน Shell และคืนค่าผลลัพธ์เป็น String

โค้ดตัวอย่างพื้นฐาน

ตัวอย่างสมบูรณ์: ส่ง Argument และรับค่ากลับ

ไฟล์ Python (script.py):

import sys
import json

# รับ arguments จาก command line
name = sys.argv[1] if len(sys.argv) > 1 else "World"
age = int(sys.argv[2]) if len(sys.argv) > 2 else 0

# ประมวลผล
result = {
    "message": f"Hello, {name}!",
    "age_next_year": age + 1,
    "timestamp": __import__('datetime').datetime.now().isoformat()
}

# พิมพ์ JSON เพื่อให้ PHP parse ได้ง่าย
print(json.dumps(result))

ไฟล์ PHP:

ข้อควรระวังด้านความปลอดภัยและสิทธิ์

  • สิทธิ์การเข้าถึง: บน Linux/Unix, PHP ทำงานภายใต้ User ของ Web Server (เช่น www-data, apache) ต้องให้สิทธิ์อ่าน/รันไฟล์ Python และไดเรกทอรีที่เกี่ยวข้อง
  • ป้องกัน Command Injection: ใช้ escapeshellarg() สำหรับ Argument ทุกตัว ไม่ใช่แค่ escapeshellcmd()
  • Timeout: คำสั่งที่รันนานเกินไปอาจถูกตัดโดย max_execution_time ของ PHP
// วิธีปลอดภัยกว่า: ใช้ escapeshellarg สำหรับแต่ละ argument
$arg1 = escapeshellarg($name);
$arg2 = escapeshellarg($age);
$command = "python3 /path/to/script.py $arg1 $arg2";

ทางเลือกอื่น: proc_open (สำหรับควบคุมได้ละเอียดขึ้น)

$descriptors = [
    0 => ['pipe', 'r'],  // stdin
    1 => ['pipe', 'w'],  // stdout
    2 => ['pipe', 'w']   // stderr
];

$process = proc_open('python3 script.py', $descriptors, $pipes);

if (is_resource($process)) {
    // ส่งข้อมูลเข้า stdin ถ้าต้องการ
    fwrite($pipes[0], $inputData);
    fclose($pipes[0]);
    
    $output = stream_get_contents($pipes[1]);
    $errors = stream_get_contents($pipes[2]);
    
    fclose($pipes[1]);
    fclose($pipes[2]);
    
    $returnCode = proc_close($process);
    
    if ($returnCode !== 0) {
        error_log("Python script failed: $errors");
    }
}