คุณสามารถใช้ PHP เพื่อ หยุดและเริ่ม service ใหม่ใน CentOS 9 ได้ โดยใช้ shell_exec() หรือ exec() ซึ่งจะรันคำสั่งของระบบ Linux ผ่าน PHP
✅ ตัวอย่างโค้ด PHP: หยุดและเริ่ม service ใหม่
<?php
$services = [
'home411cam01.service',
'home411cam02.service',
'home411cam03.service',
'home411cam05.service',
'home411cam06.service',
'home411cam10.service'
];
foreach ($services as $service) {
// หยุด service
shell_exec("sudo systemctl stop $service");
// เริ่ม service ใหม่
shell_exec("sudo systemctl start $service");
// หรือจะใช้ restart แทนก็ได้
// shell_exec("sudo systemctl restart $service");
echo "Restarted $service\n";
}
?>
✅ สิ่งที่ต้องทำเพิ่ม:
- สิทธิ์ sudo: เว็บเซิร์ฟเวอร์ (Apache/Nginx) ที่รัน PHP ต้องมีสิทธิ์
sudo
โดยไม่ต้องถามรหัสผ่าน - แก้ไข sudoers:
เปิดไฟล์/etc/sudoers
ด้วยคำสั่ง
sudo visudo
แล้วเพิ่มบรรทัด (แทน apache
ด้วย user ที่รัน PHP เช่น www-data
, nginx
, หรือ apache
)
apache ALL=(ALL) NOPASSWD: /bin/systemctl
3. ความปลอดภัย: หลีกเลี่ยงการเปิดให้ผู้ใช้จากเว็บเรียกคำสั่งนี้ตรง ๆ เพราะอาจถูกโจมตีได้
✅ ทางเลือก: ใช้ restart
แทน
shell_exec("sudo systemctl restart $service");
จะสะดวกกว่าเพราะรวม stop
+ start
เข้าไว้ด้วยกัน
ได้เลยครับ! ด้านล่างเป็นตัวอย่าง HTML + PHP แบบง่ายที่มีปุ่มให้กดเพื่อ restart
service ทีละตัว หรือทั้งหมด
🔧 index.html
– หน้าเว็บ HTML ปุ่ม
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Restart Services</title>
</head>
<body>
<h2>Restart Camera Services</h2>
<form method="post" action="restart.php">
<button type="submit" name="service" value="home411cam01.service">Restart cam01</button>
<button type="submit" name="service" value="home411cam02.service">Restart cam02</button>
<button type="submit" name="service" value="home411cam03.service">Restart cam03</button>
<button type="submit" name="service" value="home411cam05.service">Restart cam05</button>
<button type="submit" name="service" value="home411cam06.service">Restart cam06</button>
<button type="submit" name="service" value="home411cam10.service">Restart cam10</button>
<br><br>
<button type="submit" name="service" value="all">Restart All Services</button>
</form>
</body>
</html>
🧠 restart.php
– รันคำสั่ง PHP เพื่อรีสตาร์ท service
<?php
$all_services = [
'home411cam01.service',
'home411cam02.service',
'home411cam03.service',
'home411cam05.service',
'home411cam06.service',
'home411cam10.service'
];
$selected = $_POST['service'] ?? '';
if ($selected === 'all') {
foreach ($all_services as $service) {
shell_exec("sudo systemctl restart $service");
echo "Restarted $service<br>";
}
} elseif (in_array($selected, $all_services)) {
shell_exec("sudo systemctl restart $selected");
echo "Restarted $selected<br>";
} else {
echo "Invalid service name!";
}
?>
🔐 อย่าลืม:
- ตั้งสิทธิ์ให้ web server (เช่น apache, nginx) สามารถใช้
sudo systemctl
ได้โดยไม่ต้องใช้รหัสผ่าน - เพิ่มใน
sudoers
:
sudo visudo
แล้วใส่:
apache ALL=(ALL) NOPASSWD: /bin/systemctl
เปลี่ยน apache
ตามชื่อผู้ใช้ที่เว็บคุณรันอยู่ (เช่น www-data
, nginx
)