And how much the person on a site?
All of kind time of day!
For certain, walking on a network in searches porn..., i.e. in searches of any information, you have come across such chesspiece, type:
On a site: 100 person
I.e., when approximately in such context the quantity{amount} the person, present at present on a site is deduced. When I for the first time have seen such feature, she seemed to me interesting and simpotnoj.
Recently, on personal need, it wanted to me to make such for the site and I realized all this put with use PHP+MySQL. On our portal Progers.ru you can see (above) a flaunting inscription about quantity{amount} of users On-Line.
So, in this clause{article} I want to tell to you how to make such feature for a site. It actually is easier than fried cabbage; =) and soon you are convinced of it.
All that is necessary for us, it - a hosting with support PHP and MySQL and pair minutes of time. Perhaps, the some people will object, what for here a database when all can be realized on files. I shall say to you, that MySQL in the given concrete case approaches as well as possible. With use of files, it should to write much more a code and to be engaged in the majority in routine, which to us to anything; while with the help of a database all is done{made} pair - other of searches...
I hope, that you are able though somehow to address with MySQL server and know as a whole, that such databases and for what they serve. Otherwise, I can not help anything, except for how to advise to address to the friends owning art to make SQL-searches... Though, basically, you can simply copy my code and all. However, the database nevertheless should be adjusted...
So, gradually we pass from the theory to practical ehpostasi. In PHP, unfortunately (and in other server languages of web - programming), is absent such, in my opinion, useful technology which would allow to define{determine} the moment of time, in which person has left{abandoned} a site. Never mind, what way, he has made it: has closed a window of a browser or has passed under other link. Time PHP gives in, we shall make some similar technology; naturally, about accuracy and absence of errors here I do not speak... However, all so are done{made} also by us so shall make. Further I shall describe, how we shall be to define{determine}, actually, kol-in users on a line theoretically (not concerning MySql and PHP it is concrete). If you catch an idea immediately realize this opportunity in any language of web - programming and any method accessible to you (files, for example)...
For the beginning, we need to establish variable Accuracy - time during which the visitor will be considered on a line, i.e. wandering on a site.
Means, at call on page, we should define{determine} at first - napervo zashedshego IP-address and it timestamp. Any exotic, TimeStamp is a performance of time which is equaled " kol-vu the seconds past{last} since midnight on January, 1, 1970 across Greenwich till the present{true} moment ". This rather universal performance of time and, in particular, with this format works majority PHP-KH kh-® for job with "date - time". Rather convenient label, believe me on a word. I.e., than number TimeStamp there is more, than longer " we live " and than more " now time ", I apologize for confusion.
The ambassador, we open any storehouse (files, databases, a sessional file, etc.) and delete from him all recordings (each recording - the information on one zashedshem on a page the user), in which TimeStamp + Accuracy less current TimeStamp'b or where the IP-address coincides with current Ip'¼. I.e., we destroy old recordings.
Further we write down the data about zashedshem the user (we leave recording): IP and timestamp.
Everything, we count up quantity{amount} of recordings is and is kol-in the person on a site at present.
To tell the truth, it has turned out so, that the reference point was all the same conducted on MySQL, instead of on files. Really, whether our it put, all over again to climb in a file and to delete there, then again to climb in him , to write down, and then only to read out. Where it is easier to count all over again a file in a file, to remove from a file old recordings and to add recording about the user if it is required and to write down then a file back in a file. At a conclusion given to be guided kol-¼ values in a file.
I hope, all of you have caught the basic idea. We simply count up kol-in juzverej since which time of call has not passed time which we have established (Accuracy).
So, we pass at last to practice. I shall be repeated, for storage of the information there will be juzat`sja base MySQL. For all this affair we shall create the separate table. We shall name her online. In the table we shall create 3 fields:
1. id - key avto_inkrementirujuhheesja a field such as INT with maximal the sizes in 10 symbols. It is necessary for more optimized job with tablicoj though it{he} can and be lowered{omitted}. At each call of the person by a site, a field will increase the value on 1.
2. ip - a field of character type VARCHAR with the maximal value 20 cimvolov (personally I did not see still the IP-address, the size than 15 symbols there are more, but just in case =). In him are stored{kept}, accordingly, IP'HH people. A default value - 0.
3. unix - a field of character type VARCHAR with the maximal value of 60 symbols. A field in which it will be stored{kept} timestamp the user. Such strange name is expressed more likely by my personal predilections, than his true applicability. Though I shall say, that the timestamp-format is accepted in operational systems UNIX, as standarnyj. Can name a field somehow (only my example with it names of fields). On a default empty value.
I shall notice, that the field unix will have type VARCHAR, instead of type TIMESTAMP built - in by developers MySQL. It is connected to that, that this type is too inconvenient for a data storage daty\vremeni in base as it can seem at first sight.
Further I bring search, having executed which, you will create the corresponding table with the necessary fields. The search can be executed function PHP mysql_query (), or in any convenient ubolochke for job with MySQL. For example in PHPMyAdmin.
CREATE TABLE ` online ` (
` id ` int (10) NOT NULL auto_increment,
` ip ` varchar (20) NOT NULL default ' 0 ',
` unix ` varchar (60) NOT NULL default ",
KEY ` id '(' id `)
)
Have executed? Good fellows. I shall remind, that it is the best way to get used to write commands of syntax MySQL in the top register and not for ponta as the some people think, and for increase udobochitaemosti a code and it is simple because so it is accepted.
After performance of search, we need to write only a code which will be engaged, actually, calculation kol-b the person on a line. This code I have pushed in separate function which is stored{kept} at me in a file, and a file inkljuditsja (include (), require ()) on each page of my site somewhere right at the beginning. I bring to you an example of function exactly what I have written for the site, unless only little bit changed with a view of public use. At presence of necessary knowledge, you can easily edit her under yourselves.
* ------the File online.php
/* kh-n counts up users on a line; returns kol-in users in the formatted kind, i.e. for a conclusion of result it is necessary to register only in the necessary place of type: echo on_line (); */
function on_line () {
$host = "localhost"; // a host where database MySql is located
$db_name = " "; // a name of a database; as a rule coincides with a name of the user (a variable below), though I categorically against identical names, being guided on protection...
$db_user = " "; // the user to whom access to base is resolved{allowed}
$db_password = " "; // the password of the user
$wine = 300; // accuracy online (seconds); time, during which user, zashedshego on a page, we count taking place on a site
$table_online = "online"; // a name of the table
// We do{make} accessible a global variable of the IP-address
global $REMOTE_ADDR;
// We are connected to MySQL server and it is chosen the necessary base
mysql_connect ($host, $db_user, $db_password) or die (mysql_error ());
mysql_select_db ($db_name) or die (mysql_error ());
// We delete everyone who has already stayed $wine seconds or at whom IP current
$sql_update = " DELETE FROM $table_online WHERE ` unix ` + $wine <" .time (). " OR ` ip '=' $REMOTE_ADDR ' ";
$result_update = mysql_query ($sql_update) or die (mysql_error ());
// We insert the recording
$sql_insert = " INSERT INTO $table_online VALUES (", ' $ REMOTE_ADDR ',' " .time (). " ') ";
$result_insert = mysql_query ($sql_insert) or die (mysql_error ());
// We count unikov online
$sql_sel = " SELECT ` id ` FROM $table_online ";
$result_sel = mysql_query ($sql_sel) or die (mysql_error ());
$online_people = mysql_num_rows ($result_sel); // kol-in On-Line users
$online_people = (string) $online_people; // it is resulted{brought} to line type (so it is necessary.. See further)
$rain = strlen ($online_people) - 1; // number{room} of last symbol among on-line users
// Formatting a conclusion (I have made all for you =)
if ($online_people [$rain] == 2 || $online_people [$rain] == 3
|| $online_people [$rain] == 4
|| (strlen ($online_people)! =1 ** $online_people [strlen ($online_people)-2]! =1))
$line = "person"; else $line = "person"; // $line - a variable determining a format of a conclusion
// vozvrahhem result
return " On a site <strong> ". $online_people. " </strong> $line ";
}
Such function. Somewhere in the beginning of a file you should insert her somehow on type:
include ' online.php ';
And in that place where it is necessary to deduce{remove} kol-in users to write:
echo on_line ();
Now I shall explain a few{a little;little bit} code of function as in her I all is detailed otkommentiroval. First there are the variables necessary for a successful connection to base, and also a variable $wine - our accuracy. Also the global variable $REMOTE_ADDR which returns the IP-address of a client computer is done{made} accessible of function. The ambassador there is a connection with MySQL server. And already after the most interesting begins.
The first search to base (searches are carried out kh-® mysql_query ()) we delete all recordings, in which timestamp + $wine less current timestamp or in which the IP-address coincides with ours. I.e. we delete from the table either old users, or ourselves to not repeat.
The second search we insert the recording with the IP'¼ and timestamp'¼. Pay attention, that value of the first field we leave empty as it inkrementiruetsja from an insert to an insert and will by itself be filled (increased by 1 previous value).
After all manipulations with tablicoj, in her remains really true kol-in the person on a site from the moment of which arrival has not passed $wine seconds. We need to choose only simple search all recordings and to count up them kol-in. It also will be kol-in users in Online. Pay attention, that we with you as people clever, we we do not choose at once all fields from all recordings (what for to us the superfluous data if it is necessary to count up only quantity{amount} of recordings), and we choose only a field id. It too reception for optimization of searches though many overlook about him or do not know.
And then there is, actually, a formatting of the data. In my opinion, I have made his very laconic and elegant. To look pleasantly, though from the first and not absolutely understandably as there is a process. Probably, such formatting is not required to you. Suddenly you want as - or in another way to deduce{remove} the information about kol-in juzverej. Then to you it is necessary or to clean{remove} formatting, or podredaktirovat` it (including under the design). Anyhow, the variable $online_people stores{keeps} kol-in users and you everything are farther are free to do{make} with her, that want. Can simply return her (return $online_people;) and a data format to carry out at a direct conclusion, instead of in a body of function, or in general as I already spoke, to fail formatting:
echo " On-Line: " .on_line ()
It is possible, so even it will be more beautiful.
The important remarks:
? The variable $wine on my site is equal to 300 seconds, i.e. 5 minutes. You can expose its{her} value any way.
? At a connection to base and performance of searches we use a design or die () which in case of unsuccessful action finishes the script, but before it deduces in a target stream (browser) any line. In our case we use kh-¯ mysql_error () which returns the mistake which has happened during manipulation with bazoj\tablicoj in a line kind. If you do not want to finish the script (really, what for it is necessary: in fact because of one mistake in kh-¿ the site will cease to work!) simply do not use this design. As at any mistake and presence of this design, the user, it is possible (if a mistake at connection with the server), can learn{find out} some data of your MySQL server, namely a host, a login of the user and a name of base that is fraught with breaking of a site (I the pessimist at heart - do not believe me).
? $online_people we result{bring} a variable in line type, so at a format of the information (to check what to deduce{remove}: "person" or) we " twist "person" in the line "! As we twist - I think, will understand, after the some brozhzhenija brains:-). Probably, it was possible to make all more elegantly and to write less code - I do not know... If you so consider, write on a e-mail with a code which, in your opinion, is better than mine... Or leave comments to this clause{article}. I them look through sometimes (periodically once a half-year... =)
? c-n time () is engaged in that, that returns time in the seconds, past since midnight on January, 1, 1970 across Greenwich till the present{true} moment. But we know that, that on scientific it is called TimeStamp... $-)
? I have divided{shared} formatting by symbols of transition of a line, since a line of checks (where it is a lot of signs || =) very long, and it results in a stretching of clause{article} at width therefore it becomes very inconvenient to make reading of clause{article} since eyes run there - sjuda-obratno (I not that you have thought). Voobhhem you have understood me.
? A code the worker - at me same =) But: some additions have been made only at a spelling of clause{article}, in particular:
- For a connection variables are added to base and the connection occurs inside function. Naturally, at me on a site he occurs long before it and kh-n, using open connection with a MySQL-demon, carries out searches.
- I have divided{shared} formatting by a symbol of translation of a line (the reason see above) so if the script will not earn and will give out a stupid{blunt} mistake, such as parse error in... transform a line of checks to a single whole (that on one line all was). But, I think, you have understood me.
- Mistakes are improbable, but possible{probable}, as I corrected kommenty, etc. at a spelling of clause{article}, suddenly any symbol of a semicolon has forgotten. Correct all 5 =).
From additions, perhaps, all. And clause{article} comes Ze End. It is glad, that you have read up the grant{manual} up to this place, and the even greater aesthetic pleasure to me priniset that fact, that clause{article} seemed to you entertaining and has left good impressions and knowledge in bash... To a head. If you have noticed oshibki\netochnosti\bagi in clause{article} or at you something has failed, leave kommenty below or write on a soap. I necessarily shall listen you and I shall answer. Naturally, I shall be glad also to kind wishes. As without them. Though criticism priniset to me the big advantage{benefit}...
fukncii calculation of visitors On-Line you can see an example of job on our portal - Progers.Ru. Besides here you can find many good clauses{articles} and directories on programming, in particular, on PHP, with use MySQL.
On it let to be excused to you and to wish good luck and... Certainly, a passing code!
