了解外部呼叫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 發表在 痞客邦 留言(0) 人氣()