關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • 用 PHP 監察伺服器狀態

    Posted on October 6th, 2006 Sam Tang 1 comment

    要用 PHP 監察伺服器的是否在線十分簡單,可以單純呼叫系統指令並用 ping 指令便可以,但缺點是主機會不回應 ping 請求。

    而另一個方法則是用 fsockopen() 函式來做,而 fsockopen() 的功能是開啟 Internet 或 Unix domain socket 連線,以下是具體實現方法:

    CODE:
    1. <?php
    2. $fp = fsockopen("www.example.com", 80, $errno, $errstr, 10);
    3. if (!$fp) {
    4.    echo "ERROR: $errno - $errstr<br />\n";
    5. } else {
    6.    echo 'Server is online';
    7. }
    8. ?>

    以上的程式碼會檢查主機 www.example.com 上的 port 80,並設定 10 秒沒有回應便停止嘗試連線。如果連線失敗會將錯誤編號儲存在 $errno 變數,而錯誤訊息則會儲存在 $errorstr。


     

    One response to “用 PHP 監察伺服器狀態”

    1. Hello, I am from taiwan, these days i am learning php.
      I think ur website is helpful~ thx for sharing~ XD

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word