這是一種方法實(shí)現(xiàn)計(jì)數(shù)器。想看另一種方法的請(qǐng)點(diǎn)擊:【PHP】簡(jiǎn)單的網(wǎng)站訪問(wèn)量計(jì)數(shù)器實(shí)現(xiàn)
想看具體代碼思路的也請(qǐng)點(diǎn)擊上面的鏈接。
創(chuàng)建Embed-Count文件夾
在Embed-Count文件夾下面創(chuàng)建counter.inc.php文件,內(nèi)容如下:
<?php function counter(){ $counter = 0; //初始化變量 $max_len = 8; $lj = explode("/",$_SERVER["PHP_SELF"]); //超全局變量$_SERVER['PHP_SELF']保存了當(dāng)前運(yùn)行腳本的名字 Embed_Count/al_Embed_Fn.php $CounterFile="./counter/".$lj[count ($lj)-1].".dat"; if(!file_exists($CounterFile)){ if(!file_exists(dirname($CounterFile))){ mkdir(dirname($CounterFile),0777); } $cf = fopen($CounterFile,'w'); fputs($cf,'0'); fclose($cf); } else{ $cf = fopen($CounterFile,'r'); $counter = trim(fgets($cf,$max_len)); fclose($cf); } $counter++; $cf = fopen($CounterFile,'w'); fputs($cf,$counter); fclose($cf); echo $counter; } ?>
在Embed-Count文件夾下面創(chuàng)建al_Embed_Fn.php文件,內(nèi)容如下:
<?php include "counter.inc.php"; ?> <html> <head> <meta charset="UTF-8"> <title>嵌入式網(wǎng)頁(yè)計(jì)數(shù)器-劉佳晨</title> </head> <body> <div id="dd"> <span>歡迎您!</span> <span>您是本網(wǎng)站的第<?php counter(); ?>位訪客</span> </div> </body> </html>
好了,鍵入完成之后,是不是發(fā)現(xiàn)就只是把代碼封裝成一個(gè)函數(shù)而已?
沒(méi)錯(cuò),但是這次又用了很多新的函數(shù)和小技巧。讓我給你一 一道來(lái)。
小技巧
1.多數(shù)php程序員習(xí)慣于吧include或require 的文件擴(kuò)展名命名為“inc”;
2.$CounterFile="./counter/".$lj[count ($lj)-1].".dat";把計(jì)數(shù)器文件定位于當(dāng)前腳本所在文件夾下的子文件夾counter里面,文件以當(dāng)前腳本名稱(chēng)加“dat”為名,即al_Embed_Fn.php.dat
3.<?php include "counter.inc.php" ?>把計(jì)數(shù)器函數(shù)嵌入到網(wǎng)頁(yè)中,該段腳本應(yīng)該放在<HTML>標(biāo)記之前;counter.inc.php保存在與網(wǎng)頁(yè)相同的文件夾下,否則在include 中要指明文件的存放路徑
4.<?php counter(); ?>調(diào)用counter() 函數(shù),該函數(shù)返回計(jì)數(shù)器的值
好了,這個(gè)函數(shù)調(diào)用的嵌入式也做好了。
這里有幾個(gè)函數(shù)需要說(shuō)一下。
mkdir(dirname($CounterFile),0777):建立以$CounterFlile的值為名的目錄,即./counter,目錄的訪問(wèn)權(quán)限是最高權(quán)限(可讀可寫(xiě)可執(zhí)行);
dirname($CounterFile):返回路徑中的目錄部分
explode('/',$_SERVER[PHP_SELF]):返回一個(gè)字符串?dāng)?shù)組,每個(gè)元素為$_SERVER[PHP_SELF]經(jīng)“/”作為邊界切割出的子字符串
count($lj):統(tǒng)計(jì)數(shù)組&lj中元素的個(gè)數(shù)
期待我的下一個(gè)版本嗎?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持。