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