Statistics on the site. We write the visit counter script.
Introduction
Surely many of you visiting various sites, pay attention to the counters that are on the sites. Statistics shows us how many people visited the resource, how many pages were shipped, how many people are on the site at the moment and so on. All this is a very useful tool, because As it allows to know the owner of the site, the relevance and rating of its resource. The more interesting and useful the resource, the more visits it has.
At the moment there are a huge number of services that offer us many tools for collecting statistics and data, as well as their analysis. All of them are very professional in carrying out their tasks, but everything started with a self-written counter that you can meet now.
If you want to understand how users are registered, I prepared a lesson in which I will write a counter for site visits, explain how to install the counter on the site and use the data for my own purposes.
Details
In order for us to write a simple counter, we will have to learn a few new functions.
* Work with files (create / read / write); * Work with sessions; * Work with the functions for creating an image; * Connecting the counter;
We will consider three options:
* Text counter hits; * Text counter of visitors; * Graphic counter of visitors;
Start
Create a folder in the folder www, the folder counter. This will be the location for storing the statistics and script file. Next, I will give you several variants of counters.
Option 1
To use the counter, we need to create an html-page, in which we will build the script. Let it be a simple page that contains information.
Save this page in the www folder and proceed to programming the counter.
Counter.php
To save the received data, we need to write it somewhere, let it be a simple text file named stat.txt.
‹?php $url = "counter/stat.txt";
The variable $ url is assigned the address to the file. This is the only configuration element in which we specify the required data, then the script consists of the logical else else expressions and the file handling functions
This code snippet is responsible for checking for the presence of a file, I wrote the entire course of logical actions in the comments.
if(!file_exists($url)) { //Проверка на существование файла. //Если файла не существует, $count = 0; $handle = fopen($url,"a");//создаем его, fwrite($handle,$count);// и записываем нулевое значение fclose($handle);//Закрываем файл }
Next, we describe the condition when the file is created.
else { //Если файл существует, то работаем с ним $handle = fopen($url,"a+"); //Открываем его $count = fread($handle,filesize($url)); //Читаем данные и присваеваем их переменной $count fclose($handle); //Закрываем $count++;//Добавляем одно посещение к полученному выше $handle = fopen($url,"w"); // Открываем файл, и урезаем его до нулевой длины fwrite($handle,$count); //Записываем переменную $count fclose($handle); //Закрываем }
In this fragment the visit counter script is described, carefully look, in the first fragment we open the file in order to open it and find out the number of visits. Next, we increase the value by 1 unit ($ count ++;) and write this value to our file.
At the end of the file, we print statistics using the echo statement
echo "количество просмотров: $count ";
We considered the simplest type of counter, but believe me, sometimes it is more difficult and not required, for example, we need to know the number of page readings (articles, ads) inside the site. Usually this indicates the visitors of the site the most interesting material. Further, in order for this counter to work, open our index.php file, and add a line to the tag
* Easily wind up with a simple page refresh (F5). * If several people simultaneously access the script, an error will occur. The file is opened and used by someone else, so you need to add the script. * If the data file is deleted, you will lose the accumulated statistics
Option 2
Counter that counts only visitors. What does it mean? Visitors - this is the number of users who visited your resource, for example for a day, and even if a person updates the page, the value of visits will not be added.
To create such a counter, we need to learn how to work with sessions. What's the point? If a person visits your site for the first time, a session is created, which works until the person closes the browser, i.e. When the page reloads later (F5) or crosses the site, we will check whether the session was created. If the session exists, then we will not consider the user.
This option is slightly improved compared to the first option.
Pay attention to the beginning of the file, the session_start () function initializes the session.
Counter.php
In this fragment, in comparison with the first one, we leave everything unchanged
<? Php
$ Url = "counter / stat.txt";
If (! File_exists ($ url)) {
// If the file does not exist, create it, and write a null value
$ Count = 0;
$ Handle = fopen ($ url, "a");
Fwrite ($ handle, $ count);
Fclose ($ handle);
}
Here, too, just read the file, and get the number of visits. Next look carefully
Else {
// If the file exists, we work with it
$ Handle = fopen ($ url, "a +"); // Open it
$ Count = fread ($ handle, filesize ($ url)); // Read the data and assign it to the variable $ count
Fclose ($ handle);
We create a condition if the session is absent, then it means that the person visits the page for the first time, so we assign the value $ _SESSION ['count'] to some value that is checked at the beginning of the condition, then add the unit to the variable $ count, and write it back to File, and to begin with, we lock access to it, make a record and open access. This is necessary so that at the time of several visitors to the script there were no errors.
If (! Isset ($ _ SESSION ['count'])) {// If there is no session
$ _SESSION ['count'] = 1; // Create it
$ Count ++; // Add one to the variable
$ Handle = fopen ($ url, "w");
If (flock ($ handle, LOCK_EX)) {
Fwrite ($ handle, $ count); // Write it to a file
Flock ($ handle, LOCK_UN); // unlock the file
} Else {
Echo "Repeat later";
}
Fclose ($ handle);
}
}
// Display the number of views.
Echo "number of views: $ count";
?>
Now I will explain why when I press F5, I do not add a visit. Since the first time we create a session, as a result of checking if (! Isset ($ _ SESSION ['count']) the expression will return FALSE, therefore nothing will be added and written .
[+] Pros:
* Easy installation * Does not require a database * Do not crank out the page refresh * When multiple people are accessing the script at the same time, there is no error.
[-] Cons of this counter:
* If the data file is deleted, you will lose the accumulated statistics
Bonus
In this version, we'll look at a script that will build a graphic image that will display the number of visitors. For this we need a substrate for our counter, this should be a jpeg format image, you can take this for testing.
Next, we need to refine the second option, and add another file, which will be responsible for building the picture.
Counter.php - Here is a set of functions for working with images
<? Php
// Substrate for the counter
$ Im = ImageCreateFromJpeg ("bg.jpg");
// Text color
$ Black = imagecolorallocate ($ im, 255,255,255);
// Drawing the text
Imagestring ($ im, 1,8,4, $ _ GET ['s', $ black);
Header ("Content-type: image / jpeg");
// Output image
ImageJpeg ($ im);
// Destroy the image so that the memory is not clogged
Imagedestroy ($ im);
?>
All these three options are sure to come in handy in the future.
[+] Pros:
* Easy installation * Does not require a database * Do not crank out the page refresh * When multiple people are accessing the script at the same time, there is no error. * Beautiful, customizable appearance.
[-] Cons of this counter:
* If the file with stat.txt data is deleted, then you will lose the accumulated statistics
Conclusion
All the described options can be easily applied in practice, in order to output the counter simply put the code <? Php @include (counter.php);?> In the right place
UPGRADE Counter - Graphic counter hits and visits.
Details
To modify the counter, we need to master:
* Work with the setcookie () function and the $ _COOKIE superglobal; * Arrays in PHP; * Functions of image building in PHP; * Work with files and MySQL databases.
Option 1. Counter on files
The entire counter will consist of several files:
* Index.php - the page where the counter is called * Counter.php - script with logical operations and data reading / writing functions * Img.php - image building script * Stat.txt - file containing statistics
Index.php
A standard file containing the html-code, and the connection of the counter script
Also in this file at the very top of the page, before the tags and you need to set the cookie (cookies).
The first attribute of the function is the name of the cookie, the second attribute is the value assigned to this name, i.e. If you run echo $ _COOKIE ['freshcoder'], the browser displays the word count. The third attribute sets the time the cookie is active, i.e. If a person entered at 10am, we need to set a cookie for 14 hours. The action time is specified in seconds.
<? Php setcookie ("freshcoder", "count", time () + (24-date ('G')) * 3600);?>
<Html>
<Head>
<Title> Example of the counter operation </ title>
</ Head>
<Body bgcolor = "white" text = "black" link = "blue" vlink = "purple" alink = "red">
<P> Welcome </ p>
<? Php @include ("counter.php");?>
</ Body>
</ Html>
Counter.php
This script has undergone some changes. As a protection against cheating, the condition for checking the presence of cookies on the user's side is used.
For example, a person came to the site at 10 am, we need to add one visit and leave cookies in this person's browser, which will be valid until 0.00 hours of the current day.
The logic of the script is simple, if there are no cookies for the user, we wind the counter by one and write the value to a file, otherwise we add a hit.
<? Php
$ Url = "counter / stat.txt";
If (! File_exists ($ url)) {
// If the file does not exist, create it, and write a null value
$ Count = "0 :: 0";
$ Handle = fopen ($ url, "a");
Fwrite ($ handle, $ count);
Fclose ($ handle);
}
Else {
// If the file exists, we work with it
$ Data = file ($ url); // Open it
List ($ user, $ hit) = explode ("::", $ data [0]); // Break the array into variables
If (! $ _ COOKIE ['freshcoder']) {$ user ++; $ hit ++;}
Else {$ hit ++;}
$ Handle = fopen ($ url, "w"); // Open the file
$ Count = $ user. "::". $ Hit; // Form the string
If (flock ($ handle, LOCK_EX)) {// Lock the file
Fwrite ($ handle, $ count); // Write it to a file
Flock ($ handle, LOCK_UN); // unlock the file
} Else {
Echo "Repeat later";
}
Fclose ($ handle);
}
// Display the number of views.
Echo '<img src = "img.php? U ='. $ User. '& H ='. $ Hit. '" Alt = "stat" width = "80" height = "30" border = "0" /> ';
?>
Img.php
This script has undergone significant changes. Because Function imagestring (), when constructing the caption for the origin uses the upper-left corner, then with time, as the length of the string of digits increases, we will have a problem - some of them will vylazit for the image. In order for this to happen, we write simple conditions that get the data, compare them, and call the imagestring () function with the changed coordinates.
Also in the script we add the second line to build the inscription. This script receives data using the GET parameter, so
We will extract the data from the superglobal $ _GET.
Img.php? U = '. $ User.' & H = '. $
Hit .' " In this line, we set $ _GET ['u'] to $ user, and $ _GET ['h'] to $ hit . This is a very simple way of giving parameters to a script. But this method is not recommended for passing a password or any important data.
<? Php
// Substrate for the counter
$ Im = ImageCreateFromGif ("bg.gif"); </ p>
// Text color
$ Black = imagecolorallocate ($ im, 255,255,255);
// Draw the number of visitors
If ($ _ GET ['u']> = 1 AND $ _GET ['u'] <10) {
Imagestring ($ im, 2,69,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 10 AND $ _GET ['u'] <100) {
Imagestring ($ im, 2,64,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 100 AND $ _GET ['u'] <1000) {
Imagestring ($ im, 2,59,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 1000 AND $ _GET ['u'] <10000) {
Imagestring ($ im, 2,54,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 10000 AND $ _GET ['u'] <100000) {
Imagestring ($ im, 2,49,14, $ _ GET ['u'], $ black);
}
// Draw the number of hits
If ($ _ GET ['h']> = 1 AND $ _GET ['h'] <10) {
Imagestring ($ im, 2,69,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 10 AND $ _GET ['h'] <100) {
Imagestring ($ im, 2,64,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 100 AND $ _GET ['h'] <1000) {
Imagestring ($ im, 2,59,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 1000 AND $ _GET ['h'] <10000) {
Imagestring ($ im, 2,54,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 10000 AND $ _GET ['h'] <100000) {
Imagestring ($ im, 2,49,3, $ _ GET ['h'], $ black);
}
Header ("Content-type: image / gif");
ImageGif ($ im);
Imagedestroy ($ im);
?>
Here is the counter for accounting for page transitions and indicating the actual number of visitors.
Option 2. Counter on MySQL
First you need to create a table in which we will store all the data. If you are testing on a local server, the query will be as follows:
When working with a database, only the file counter.php will be changed
Counter.php
In this example, everything is much simpler. The first step is to connect to the database.
<? Php
// Connect to the database.
$ Db = @ mysql_connect ("localhost", "root", "pass") or die ("Connection error");
@mysql_select_db ("test", $ db) or die ("Can not select a database");
$ Q = mysql_query ("SELECT * FROM counter");
$ R = mysql_fetch_array ($ q);
If (! $ _ COOKIE ['freshcoder'])
{
$ R ['hosts'] ++; $ R ['hits'] ++; // If there is no cookie, add value
}
Else {$ r ['hits'] ++; } // If there are cookies, then just add the hits
Mysql_query ("UPDATE counter SET hosts =". $ R ['hosts']. "', Hits = '". $ R [' hits']. "'");
Echo '<img src = "img.php? U ='. $ R ['hosts']. '& H ='. $ R ['hits']." "Alt =" stat "width =" 80 "height = "30" border = "0" /> ';
?>
Using the mysql_fetch_array function, we get an array $ r whose keys are the fields of the counter table. The variable $ r ['hosts'] is visitors, and $ r ['hits'] are hits. As with files, we use conditions and cookie checks, if they do not exist, then increment the variable $ r ['hosts'] by one, if we exist, we increase the variable $ r ['hits'].
Next is a query that updates the record and inserts the values. After that, we display the picture script.
Img.php
We leave without changes.
<? Php
// Substrate for the counter
$ Im = ImageCreateFromGif ("bg.gif"); </ p>
// Text color
$ Black = imagecolorallocate ($ im, 255,255,255);
// Draw the number of visitors
If ($ _ GET ['u']> = 1 AND $ _GET ['u'] <10) {
Imagestring ($ im, 2,69,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 10 AND $ _GET ['u'] <100) {
Imagestring ($ im, 2,64,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 100 AND $ _GET ['u'] <1000) {
Imagestring ($ im, 2,59,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 1000 AND $ _GET ['u'] <10000) {
Imagestring ($ im, 2,54,14, $ _ GET ['u'], $ black);
}
If ($ _ GET ['u']> = 10000 AND $ _GET ['u'] <100000) {
Imagestring ($ im, 2,49,14, $ _ GET ['u'], $ black);
}
// Draw the number of hits
If ($ _ GET ['h']> = 1 AND $ _GET ['h'] <10) {
Imagestring ($ im, 2,69,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 10 AND $ _GET ['h'] <100) {
Imagestring ($ im, 2,64,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 100 AND $ _GET ['h'] <1000) {
Imagestring ($ im, 2,59,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 1000 AND $ _GET ['h'] <10000) {
Imagestring ($ im, 2,54,3, $ _ GET ['h'], $ black);
}
If ($ _ GET ['h']> = 10000 AND $ _GET ['h'] <100000) {
Imagestring ($ im, 2,49,3, $ _ GET ['h'], $ black);
}
Header ("Content-type: image / gif");
ImageGif ($ im);
Imagedestroy ($ im);
?>
Liked? Subscribe to RSS news! You can also support shram.kiev.ua, press:
It will not be superfluous for your friends to learn this information, share their article with them!
Expand / Collapse
Comments
Commenting on, remember that the content and tone of your message can hurt the feelings of real people, show respect and tolerance to your interlocutors even if you do not share their opinion, your behavior in the conditions of freedom of expression and anonymity provided by the Internet, changes Not only virtual, but also the real world.All comments are hidden from the index, spam is controlled.
Comments
Commenting on, remember that the content and tone of your message can hurt the feelings of real people, show respect and tolerance to your interlocutors even if you do not share their opinion, your behavior in the conditions of freedom of expression and anonymity provided by the Internet, changes Not only virtual, but also the real world. All comments are hidden from the index, spam is controlled.