Home php教程 php手册 PHP下定制自己的记数器

PHP下定制自己的记数器

Jun 21, 2016 am 09:02 AM
counter flag int php str

 

计数器是让 Web 访客知道该网页或者网站的人气指数最直接的方法,同时,访客人数也是给广告商做广告的最好依据。虽然很多网站都提供免费的计数器,可毕竟不是自己亲手制作的,不能体现出自己的特色。下面就PHP环境下记数器的制作过程进行详细的讨论。

访客计数器的流程如下:

第一位使用者浏览某页。

服务器程式从资料库或档案中读取该页被浏览次数。

将次数加一储存,并将它送回第一位使用者。

下一位使用者浏览某页。

服务器程式从资料库或档案中读取该页被浏览次数。

将次数再加一储存,并将它送回下一位使用者。

PHP中没有直接的计数器函数,但利用它强大的功能,我们可以很容易地自己编写一个计数器。计数器的实现分为两个阶段:一是实现计数;二是实现数字的显示。在实现计数时又有两种方式:一是基于文件的计数方式;二是基于数据库的计数方式。同样在实现数字的显示上也有两种方式:一是普通的文本显示;二是图形方式显示。下面就分别将这四种情况作一一介绍.

一、计数的实现

1.基于文件的计数

原理:把以往的访问人数记录在一个文本文件中,当网页被访问的时候,打开该文件并从中读出以往的访问人数,加 1,得到最新的访问人数,再把最新的访问数字回写到纪录访问人数的文件中。
实现;

php

$counterFile = "counter.txt";
if (!file_exists($counterFile)) {
//判断文件是否存在
$fp = fopen($counterFile, "w");
fputs($fp, "0");
fclose($fp);
}
//读文件
$n=10;
$fp = fopen($counterFile, "r");
$str1 = fgets($fp,$n);
$str1++;
fclose($fp);
//回写文件
$fp = fopen($counterFile, "w");
fputs($fp, $str1);
fclose($fp);

?>

程序说明:在浏览到本页时,PHP 程式先找寻 counter.txt 文件是否存在,若不存在,则建立一个 counter.txt 文件,并将 0 写入文件。然后读取 counter.txt 文件的内容,并将读出的数字加一,然后回写到文件中。

2、基于数据库的计数

原理:把访问人数记录在一个数据库中,当网页被访问的时候,从数据库中读出以往的访问人数,加 1,得到最新的访问人数,再把最新的访问数字回写到数据库中。

实现:假设数据库为Mysql数据库,名为XinXiKu,先建一数据表count,表字段中仅有counter一个字段,默认值为0,来记录访问人数。

php

//连接数据
$db=mysql_connect("localhost","root","");
mysql_select_db("XinXiKu",$db);
//更新访问人数
$result=mysql_query("update count set counter=counter+1",$db);

?>

程序说明:访问者在浏览到本页时,首先连接到数据库,并把记数字段用原值加1来进行更新操作,实现访问数的递增。

二、记数的显示

1、普通的文本方式显示

这种显示方法很简单,在需要显示记数的地方直接输出即可。以上面的例子分别说明:

基于文件的计数,直接输出变量str1的内容即可。
php echo $str1 ; ?>

基于数据库的计数,首先从数据库中读出,然后再输出。

php

//查询数据库
$sql="select * from count";
$result=mysql_query($sql,$db);
//取得记录集
$record=mysql_fetch_array($result);
//取得访问人数
$str1=$record["counter"];
echo $str1;

?>

同样,你也可以用html语句像 等对输出的数字进行修饰。文本显示的优点是减少下载时间,浏览速度快。缺点是显示方式不够活泼。

2、图形方式显示

原理:把读出的访问数据格式化成标准的格式,然后利用php提供的图像处理函数,把数字输出成图片格式。这样,数字的显示格式可以随意控制,真正能体现出自己的特色来。

实现:


Header("Content-type: image/gif");
//定义输出为图像类型
$n=10;
//变量$n是显示位数

//利用上面的方法,取得访问人数并赋值给变量$str1 (程序略)
$str1=取得访问人数的值
$str2 = "";
//位数如果不够$n位,在前面补0
$len1 = strlen($str1);
for ($i=1;$in;$i
++) {
$str2 = "0".$str2;
};
//得到$n位0
$len2 = strlen($str2);
//计算访问人数的位数
$dif = $len2 - $len1;
$rest = substr($str2, 0, $dif);
$string = $rest.$str1;
//位数如果不够$n位,在前面补0
for ($i=0;$i$str[$i]=substr($string,$i,1);
};
//以数组存储每位数字
$font = 4;
//定义字号
$im = imagecreate($n*11-1,16);
//新建图象
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
//定义颜色
imagefill($im, 0,0,$black);
//把计数器的底色设置成黑色
ImageString($im,$font,1,0,$str[0],$white);
for ($i=1;$iimageline($im, $i*11-1,0,$i*11-1,16, $white);
ImageString($im,$font,$i*11+1,0,$str[$i],$white);
};
//将每位写入图象,并以竖线分隔
ImageGif($im);
//图象输出
ImageDestroy($im);
//释放图象
?>

输出图形如图如示:

函数说明:

imagecreate(int x_size, int y_size):建立一张全空的图形。参数 x_sizey_size 为图形的尺寸,单位为像素 (pixel)。

imagecolorallocate(int im, int red, int green, int blue):用来匹配图形的颜色,供其它绘图函数使用。参数 im 表示图形的 handle。参数 red、green、blue 是色彩三原色,其值从 0 至 255。

imagefill(int im, int x, int y, int col):将图片坐标 (x,y) 所在的区域着色。参数 col 表示欲涂上的颜色。

imagestring(int im, int font, int x, int y, string s, int col):在图片上绘出水平的横式字符串。参数 font 为字形,设为 1 到 5 表示使用默认字形。参数 x、y 为字符串起点坐标。字符串的内容放在参数 s 上。参数 col 表示字符串的颜色。

imageline(int im, int x1, int y1, int x2, int y2, int col):在图形上画出一条实线。从 x1、y1 连接到 x2、y2,原点 (0,0) 为图形的左上角。参数 col 为实线的颜色。

imagegif(int im, string [filename]):建立一张 GIF 格式图形。参数 im 为使用 ImageCreate() 所建立的图片代码。

imagedestroy(int im):将图片 handle 解构,释于内存空间。

三、结束语

1、上述代码如果直接放在文件头,那么只要有人访问该页,无论是刷新还是从网站的其它页跳转到该页,就会使计数值加1,从而使主页计数失去了真实性。有两个很简单的办法可以解决。


a、在返回到该页的链接上传递一个参数flag,比如:index.php?flag=1,在计数之前首先检查flag变量是否已赋值,若未赋值,计数器加1。否则不加。

if(empty($flag)){
$counter+=1;
}

b、用Session记录一标志flag,在记数前先判断flag是否已赋值,如果没赋值,则记数加1,并给flag赋值,否则,记数器不变。

if (!isset($flag))
{
//处理记数器加1语句
...
//赋值flag
session_start();
session_register("flag");
$flag=1;
}

2、为了方便,可以将计数器作为一个函数MyCounter(),这样只许需在主页开头加入require("filename"); 使MyCounter()成为此主页的一部分,需要的时候,将 MyCounter();?>加在需要计数器的地方显示就可以了。

3、利用图形显示计数器时,在需要的地方直接插入:img src="counter.php" border=0>即可。但要注意的是PHP中必须安装GD库才能利用php中的图像处理函数。

 



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles