search
HomeBackend DevelopmentPHP TutorialCounter detailed design_PHP tutorial

Counter detailed design_PHP tutorial

Jul 21, 2016 pm 04:06 PM
analyzeCanBaseOverviewfrequencyprogramcountcounterdesignaccessdetailedconductpage

Overview:
This design can design a counting analysis program based on this counter, which can analyze the number of page visits and IP visits, and form a report.
1. Database design
The database uses mysql
Related files: createDatabase.sql Create database
createTblCounter.sql Create counter table


Table name: tpCounter (table of pages counter)
field:
Name Type Meaning
id Int (10) auto_increment Serial number
pagename varchar(20) Page identification, the default is page file name
count Int(10) Count Value

Table name: tiCounter (table of ip counter)
Field:
Name Type Meaning
id Int(10) auto_increment Serial number
ip varchar(20) Ip identification
count Int(10) The number of times the IP has been visited
date datetime The most recent access time
pages text The page IDs that have been visited, separated by '|'

2. Detailed description:
1. You can count each page, or you can count the number of visits to each IP, the most recent visit time, and the pages visited each time. Two tables are needed;
2. Count the number of website visitors: Set one in tpCounter Site identification [it is recommended to use the pagename='0' flag];
3. Check the session every time you open the page. If the user's session does not exist, it means that you have just started to visit this website. Create a user at this time session, the website count increases by 1, and the visited page count increases by 1; [when opening or refreshing the page] If the user session already exists, the website count value does not increase, but the page count value increases by 1 every time it is refreshed;
4. When closing the page, check whether the number of pages the user has opened on this website is 0. If so, destroy the user's session, otherwise it will not be destroyed; [This function does not require writing a program, the server automatically executes it]
5. If the page is not identified in tpCounter during the visit, a record will be automatically inserted into the table;
6. Pages is a text type that records the time the viewer visited and the page visited, which contains a string in a format similar to this:
||2001-5-1 16:00:00|1|12|5||2001-8-3 10:12:5|4|9|
means that this ip is in 2001-5-1 Visited pages 1, 12, and 5 at 16:00:00, and visited pages 5, 4, and 9 at 2001-8-3 10:12:5 [the page number is obtained from the previous table];
7, Design the counting file (.php). Each page contains this file. This file contains the following functions:
1>session check,
2>connect to the database,
3>Count [parameters are Page name, IP, current time],
4> Read and write the database,
5> Disconnect from the database;
8. The visited pages are recorded in the following way:
User When opening a new page, if the user session does not exist, write the time and record the current page. If it exists, write the current page. Writing is done in an appended manner.
9. The website count is in this header file, and the page count is in the counted pages.
10. When each page includes this file, if you want to count the pages, you must use the variable $page_name before including it, and assign it to the name of the page. Page names cannot be repeated.

3. Interface description:
Related files: counter.php

1/Boolean check_session()
Function description: session check, return true if it exists; return true if it does not exist false, and create and register the Boolean variable existing
Entry parameters: None
Exit parameters: Boolean
2/site_count($content)
Function description: Website visit count
Entry parameters : Database connection
Exit parameters: Count value

3/page_count($connect,$page_name,$flag=true)
Function description: Count of web pages, return the number of page visits, integer, $ flag is a flag indicating whether to increase the count, the default is true
Entry parameters: $connect: database connection, $page_name: web page name
Exit parameters: number of page visits


4/show_site_count( int type)
Function description: Display count
Entry parameters: type==1 uses graphic counting
type==2 uses text counting

4. Process
0/check entry Permissions of the page
Since the header file needs to be compiled by reference, it must be checked whether it is passed by reference or browsed directly
1/Link to the database
2/Check the session, if it does not exist, create the session and count the website
3/Display count
4/Perform page count
5/Disconnect from the database [automatic implementation]

5. Usage
All functions are included in one In the header file, when using it, just include this header file.
6. Attached source program
/**counter.php v1.0
* by Amio 2001-5-1
* Description: counter file, can count the entire website,
* can count all pages, can count each ip
*/
/**Interface implementation function:
* 1>session check
* 2>Connect to database
* 3>Count
* 4>Read and write database
* 5>Table output of link part
*/
/**Usage:
* This file must be included in other php files.
* You need to configure the $inc variable before quoting.
* e.g.:
* * $ inc="inc";
* include("include.php");
*
* ?>
*/
?>
//session check, return Boolean
//true - this user session exists
//false - this user session does not exist
function check_session(){
$existing=true;
session_start();
if (!session_is_registered("existing")){
session_register("existing");
return false;
} else return true;
}


//Web page count, returns the number of page visits, integer
//$flag is a flag indicating whether to increase the count, default true
function page_count($connect ,$page_name,$flag=true){
$ip = getenv("REMOTE_ADDR");
$query=@mysql_query("select id,count from tpcounter where pagename='$page_name'",$connect ) or die("invalid page query!");
if (!(mysql_num_rows($query))){
mysql_query("insert into tpcounter (pagename,count) values('$page_name',1) ",$connect)or die("insert page failed");
$pidquery=@mysql_query("select id from tpcounter where pagename='$page_name'",$connect) or die ("select page id failed" );
$pidarray=mysql_fetch_array($pidquery);
$pid=$pidarray[id]; $array=mysql_fetch_array($query );
$num=$array[count]; $pid=$array[id]; if ($flag)
$num++; mysql_query("update tpcounter set count =$num where pagename='$page_name'",$connect)or die("update page failed");
          $return_num=$num; from ticounter where ip='$ip'",$connect) or die ("invalid pages query!");
if (($flag)&&(mysql_num_rows($pquery))){
$parray= mysql_fetch_array($pquery);
$ps="$parray[pages]";
$pstr="$parray[pages]"."$pid"."|"; ticounter set pages='$pstr' where ip='$ip'",$connect)or die ("update ip failed");
}  
 return $return_num;  
}

//ip count, returns the number of ip accesses, integer
//In addition to counting, it also has time update function
//$flag is a flag for whether to increase the count, the default is true
//Note: The call to ip_count must be before page_count!!!
function ip_count($connect){

$ip = getenv("REMOTE_ADDR");

$visit_time=date ("Y:m:d:H:i");
$visit_pages="||"."$visit_time"."|";
$ipquery=@mysql_query("select count,pages from ticounter where ip='$ip'",$connect) or die ("invalid ip query!");

if (!(mysql_num_rows($ipquery))){//New ip
$ pageStr="|"."$visit_pages"; mysql_query("insert into ticounter (ip,count,date,pages) values ​​('$ip',1,'$visit_time','$pageStr')", $connect)or die("insert ip failed");
return 1;
}else{ //Old ip
$parray=mysql_fetch_array($ipquery);
$ipnum=$ parray [count];
$pageStr="$parray[pages]"."$visit_pages";
$ipnum++;
mysql_query("update ticounter set count=$ipnum,date='$visit_time', pages='$pageStr' where ip='$ip'",$connect)or die("update ip failed");
               return $ipnum; 🎜>//Site count, returns integer, number of website visits
function site_count($connect){
if (!check_session()){ //session does not exist
$ipnum=ip_count($connect );
         $num=page_count($connect,"website",true); > }  
return $num; 
}

function displayCount($num){
$fileurl="countpng.php?count=".$num;
return $fileurl ;
}

//Display count value, type is the display type, length is the displayed length, default 6
//type=1 graphic form
//type=2 text Form (default)
function show_site_count($num,$length=6,$type=2){

$outStr=strval($num);
for ($i=strlen( $outStr)+1;$i                                                                            :
echo " echo displayCount($outStr);
echo "">";
break;
case 2:
default:
echo "$outStr";
}  
}
?>

if (!isset($inc))exit;
$connect=mysql_connect('localhost','root' ,'');//connect to server
mysql_select_db("damio",$connect); //select database ,database name is damio

$sitecount=site_count($connect);
if (isset($page_name))
page_count($connect,$page_name);
?>



http://www.bkjia.com/PHPjc/315284.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/315284.html

TechArticle

Overview: This design can design a counting analysis program based on this counter, which can calculate the number of page visits and IP visits Conduct analysis and form reports. 1. Database design Database acquisition...

Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),