[心得] 外部呼叫JavaScript跟PHP(2) - 線上人밠…

看板PHP作者時間19年前 (2007/02/21 15:07), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/2 (看更多)
HTML版本 http://blog.pixnet.net/kewang/post/2860524 了解外部呼叫JavaScript跟PHP(1)之後,接下來就要做線上人數偵測。 參考了網站建置百寶箱的這篇文章之後,我們必須將程式碼的輸出部分修改為 document.writeln的方式。 大家會發現我寫的第一篇文章,裡面用到一堆的echo還有document.writeln, 因為太繁雜了,我們可以用function改寫,到時候如果有一大堆的 document.writeln我們直接呼叫print_by_js就可以了。 function print_by_js($string) { echo "document.writeln(\"$string\");\n"; } 在開發此功能時,需要建立兩個檔案ip.txt以及time.txt,權限均為666。 下面就是我改寫網站建置百寶箱文章之後的原始碼,而且我多增加了一個功能, 就是顯示你瀏覽此網站的IP。 <?php //treat the php file as javascript file Header("content-type: application/x-javascript"); //call external javascript function print_by_js($string) { echo "document.writeln(\"$string\");\n"; } //get time of day $now = gettimeofday(); $filetime = file_get_contents('time.txt'); //if time.txt is NULL, then write now['sec'] to time.txt and clear ip.txt if($filetime == '') { $f_time = fopen('time.txt', 'w+'); fputs($f_time, $now['sec']); fclose($f_time); $f_ip=fopen('ip.txt', 'w+'); fputs($f_ip, ''); fclose($f_ip); } //get time of today $filetime = file_get_contents('time.txt'); //refresh time is 60secs $threshold = ($now['sec'] - $filetime); //if refresh time is greater than 60secs, then clear time.txt if($threshold > 60) { $f_time = fopen('time.txt', 'w+'); fputs($f_time, ''); fclose($f_time); } //open ip.txt, its mode is "append" $f_ip = fopen('ip.txt', 'a+'); //get remote address $ip = $_SERVER['REMOTE_ADDR']; $flag = 1; $fileip = file('ip.txt'); $total = count($fileip); //exclusive the same IP for($i = 0; $i < $total; $i++) { if("$ip\n" == $fileip[$i]) { $flag = 0; break; } } if($flag == 1) { $ipstring = "$ip\n"; fputs($f_ip, $ipstring); } fclose($f_ip); //show onlines $fileip = file('ip.txt'); $onlines = count($fileip); print_by_js("您的IP為$ip<br />"); print_by_js("目前線上人數:$onlines"); ?> 有了這項利器,以後在開發blog的時候就非常方便了。 參考資料: External JavaScript and PHP 首頁∕PHP建構術∕線上人數統計 外部呼叫JavaScript跟PHP(1) -- 雜七雜八的kewang部落格 http://kewang.pixnet.net -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.139.56.187

02/21 15:12, , 1F
好讚。受益良多
02/21 15:12, 1F
※ 編輯: kewang 來自: 220.139.56.187 (02/21 22:52)
文章代碼(AID): #15s-_54n (PHP)
文章代碼(AID): #15s-_54n (PHP)