You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

软件测试实习生求PHP服务器定时存活检测脚本可行方案

Solid Alternatives for Server Health Monitoring (PHP + Scheduled Tasks)

Hey there! Let's start by unpacking why your initial Ajax approach got nixed—Ajax runs in the client's browser, which means it only works if someone has the page open 24/7. Plus, client-side network issues could trigger false alarms, which is probably why your senior dev shot it down.

Below are reliable server-side solutions that fit your requirement of checking server health every 10 minutes and sending alerts when it goes down:

This is the industry standard for scheduled server-side tasks. The idea is to write a standalone PHP script that checks server health, then use your server's built-in scheduler to run it every 10 minutes.

Step 1: Write the PHP Monitoring Script

Here's a robust example using curl to check HTTP availability (you can adapt it to check specific ports like SSH/MySQL too):

<?php
// Configuration
$targetServer = "your-server-domain-or-ip";
$checkPort = 80; // Use 443 for HTTPS, 3306 for MySQL, etc.
$timeout = 15; // Seconds to wait for a response
$alertEmail = "your-admin-email@example.com";
$monitorEmail = "server-monitor@example.com";

// Check HTTP status code
$ch = curl_init("http://{$targetServer}:{$checkPort}");
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_NOBODY, true); // Don't fetch full page content
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Alternative: Check TCP port connectivity (if HTTP isn't your priority)
// $socket = fsockopen($targetServer, $checkPort, $errno, $errstr, $timeout);
// $isAlive = $socket !== false;
// fclose($socket);

// Determine if server is down
$isDown = ($httpStatus < 200 || $httpStatus >= 400);

if ($isDown) {
    // Send alert email (use PHPMailer instead of mail() for better reliability)
    $subject = "⚠️ ALERT: {$targetServer} is Unreachable!";
    $message = "Server health check failed at " . date('Y-m-d H:i:s') . "\n";
    $message .= "Target: {$targetServer}:{$checkPort}\n";
    $message .= "HTTP Status Code: {$httpStatus}\n";
    
    $headers = "From: {$monitorEmail}\r\n";
    $headers .= "Reply-To: {$monitorEmail}\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    // Send email
    mail($alertEmail, $subject, $message, $headers);
    
    // Optional: Log the failure
    file_put_contents('/var/log/server-monitor.log', date('Y-m-d H:i:s') . " - DOWN: {$targetServer}\n", FILE_APPEND);
} else {
    // Optional: Log successful check
    file_put_contents('/var/log/server-monitor.log', date('Y-m-d H:i:s') . " - UP: {$targetServer}\n", FILE_APPEND);
}
?>

Step 2: Set Up the Cron Job

On Linux/Unix servers, use crontab to schedule the script to run every 10 minutes:

  1. Open the crontab editor: crontab -e
  2. Add this line (replace paths with your actual script and PHP executable paths):
    */10 * * * * /usr/bin/php /var/www/html/server-monitor.php >> /var/log/cron-monitor.log 2>&1
    
    • */10 * * * * = Run every 10 minutes
    • /usr/bin/php = Absolute path to your PHP CLI binary (find it with which php)
    • The >> ... 2>&1 part logs Cron output for debugging

2. Integrate with Existing Monitoring Tools (If Available)

If your team uses tools like Zabbix, Nagios, or Prometheus, you can leverage their built-in server health checks and configure them to trigger your PHP email alert script when a failure is detected. This saves you from building the scheduling logic from scratch.

3. Avoid These Less Reliable Options

  • PHP-based "internal" timers: Extensions like pcntl or custom loop-based timers depend on a running PHP process. If the process crashes, monitoring stops—way less reliable than system-level Cron.
  • Client-side scripts: As you learned, Ajax/browser-based checks are dependent on user activity and prone to false alarms.

Pro Tips

  • Use PHPMailer instead of PHP's native mail() function—it supports SMTP authentication, reduces the chance of alerts going to spam, and handles errors better.
  • Add a retry mechanism: Don't send an alert on the first failure. Wait 1-2 minutes and recheck 2-3 times to avoid false alarms from temporary network blips.
  • Monitor multiple endpoints: Check not just the web server, but also critical services like databases or APIs to get a full picture of server health.

内容的提问来源于stack exchange,提问作者taciturn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:10:06