Tải bản đầy đủ (.pdf) (5 trang)

Plug in PHP 100 POWER SOLUTIONS- P43 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (282.54 KB, 5 trang )


176
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s

176
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
O
ffering chat, messaging, and user interaction features are fundamental ways to
create addictive content and build up traffic to a site. The phenomenal growth of
sites such as MySpace, Facebook, and Twitter (as well as the huge increase in use of
instant messaging software) all serve to show that what Internet users love to do more than
anything else is communicate with other users.
Whether leaving messages, commenting on blogs or web sites, e-mailing, or Tweeting,
if you provide the right services, your users will not only take to them, they’ll invite their
friends along, too. And presto, you’ll now have free compelling content, as long as you treat
your users well and make your web site easy to use.
And that’s the aim of this batch of plug-ins: to provide a collection of ready-made
functions you can draw on to add the user interaction features your web site needs.
Users Online
One of the things that drives webmasters crazy is the fact that getting the ball rolling and
building up a user base is very hard, but the more users you have the easier it is to get more.
Why? One answer has to be that people don’t want to feel alone on a web site. So what
better way to reassure them than to display the number of users currently using your web
site? And that’s what this plug-in will do for you: It lists the total number of people who
have used your web site within a recent period decided by you.
Of course, at times when you don’t have many active users you may want to disable
this plug-in, or maybe increase the time span during which a visitor is considered recent.
But if you do have a few visitors online, discretely displaying the number in a sensible place
will reassure them that your web site has something going on. Figure 8-1 shows a web page
with five active users.
About the Plug-in


This plug-in reports the number of users who have recently been active. It takes these
arguments:
• $datafile A string containing the location of a file for storing the data
• $seconds The period of time, in seconds, during which a recent user is considered
active
FIGURE 8-1 This plug-in provides a quick snapshot of your site’s usage and popularity.

51
C h a p t e r 8 : C h a t a n d M e s s a g i n g
177
C h a p t e r 8 : C h a t a n d M e s s a g i n g
177
Variables, Arrays, and Functions
$ip
String containing the IP address and the User Agent of the current user
$out
String containing the contents of the datafile to be written back to the server
$online
Integer counter containing the number of users online
$users
Array containing unique user details
$usertime
String containing time the user being processed last accessed the web site
$userip
String containing the IP and User Agent string of the user being processed
How It Works
This plug-in starts by determining the current user’s IP address and User Agent string, as
provided by their browser, and then assigning the result to the string $ip. Then a couple of
variables are initialized: $out, the contents of the datafile that will be written back, is set to
the empty string; and $online, the number of users online is set to 1 (since the program

knows that at least the current user is active).
If the file $datafile already exists, then there may be previous users who have been
active within the last number of seconds specified by $seconds. In which case the contents
of $datafile are loaded in, with the last character (a \n linefeed) being removed by the
rtrim() function since it is not needed. The result is then split at each remaining \n
linefeed into the array $users, so that $users will now have one entry for each user.
A foreach loop is then used to iterate through $users, with the details of each one
being processed stored in $user. Then the list() function is used to assign $usertime
and $userip the time and IP/User Agent details for the user being processed. These are
split out of $user using the explode() function with an argument of | (the | symbol being
the separator I chose for this plug-in’s data).
Then, the current time is looked up using the time() function. If that value, less the
value stored in $usertime, is less than the number of seconds stored in $seconds, then that
user is considered to still be active, and so their details are appended to the string $out, and
the count of active users in $online is incremented.
However, if more seconds than the value in $seconds have elapsed since their last
access, then they are assumed to no longer be active and their details are forgotten by not
appending them to $out.
Note how a test is made to ensure the current user’s details are always ignored using
the code && $userip != $ip, so that the IP/User Agent details of the user being processed
are not the same as the current user’s. This is to ensure those details are removed so they
will not be duplicated when the datafile is written back to disk.
After completing, the loop $out has the current time and IP/User Agent details appended
to it from the function time() and the variable $ip, separated by a | character and terminated
with a \n newline. The contents of $out are then saved to the file $datafile, and the number
of active users in $online is returned.
How to Use It
When you want to keep a count of the active users on your web site you should include a
call to this plug-in on all your pages where the count is wanted. Doing so is as simple as
ensuring the plug-in has been included or pasted, and then using the following code:

PIPHP_UsersOnline('users.txt', 300);

178
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s

178
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
Here the 300 represents 300 seconds or five minutes, which is probably a reasonable
time window to start with. Whenever you want to know the number of active users, you
assign the result returned by the function to a variable, or simply echo it, like this:
echo "Users online: " . PIPHP_UsersOnline('users.txt', 300);
You can replace the datafile name users.txt with whatever name you prefer.
The Plug-in
function PIPHP_UsersOnline($datafile, $seconds)
{
$ip = getenv("REMOTE_ADDR") .
getenv("HTTP_USER_AGENT");
$out = "";
$online = 1;

if (file_exists($datafile))
{
$users = explode("\n",
rtrim(file_get_contents($datafile)));

foreach($users as $user)
{
list($usertime, $userip) = explode('|', $user);

if ((time() - $usertime) < $seconds &&

$userip != $ip)
{
$out .= $usertime . '|' . $userip . "\n";
++$online;
}
}
}

$out .= time() . '|' . $ip . "\n";
file_put_contents($datafile, $out);
return $online;
}
Post to Guestbook
No self-respecting web site is complete without some means of providing feedback, so
here’s a simple plug-in to enable you to offer a Guestbook feature in just a few lines of PHP
code. Figure 8-2 shows the same information posted twice, but because flooding control is
enabled, the second post is not added to the Guestbook.
About the Plug-in
This plug-in posts a message to a Guestbook. It takes these arguments:
• $datafile A string containing the location of a file for storing the data
• $name The name of the poster

52
C h a p t e r 8 : C h a t a n d M e s s a g i n g
179
C h a p t e r 8 : C h a t a n d M e s s a g i n g
179
• $email The poster’s email address
• $website The poster’s website
• $message The message to be posted

Variables, Arrays, and Functions
$data String containing a concatenation of $name, $email, $website, and $message,
separated by the token !1!
$lines Array containing the messages extracted from $datafile
$fh File handle into the file $datafile
How It Works
This plug-in takes all the data supplied to it, and if it’s not a duplicate of an existing entry,
adds it to the datafile. It begins by first creating the line of data to add to $datafile by
concatenating the values of $name, $email, $website, and $message, separating them all
by the token !1!, which I chose as being unlikely to be ever used in a message or name, and
so on. It then places the result in the string $data.
Then, if the file $datafile already exists, it is opened and its contents are extracted into
the array $lines after the final character, a \n newline character, is removed. The extraction
is performed using the explode() function with an argument of \n, newline, the points at
which to perform the splitting.
Using the function in_array(), each element of $lines is then checked to see whether
it already contains the contents of $data. If so, then this would be a duplicate entry and so a
value of 0 is returned to indicate the fact, and the post is therefore not added.
Otherwise the entry is not a duplicate, so the file handle $fh is assigned the value returned
upon opening $datafile for appending, with the fopen() function and an argument of 'a'. If
$fh is set to FALSE, then the file could not be opened and so -1 is returned to indicate that fact.
FIGURE 8-2 This plug-in provides easy posting to a Guestbook with flood control.

180
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s

180
P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s
Then the flock() function is called with a parameter of LOCK_EX (for EXclusive lock).
This forces the function to wait until all other processes have finished accessing the file. This

is done because other users could be posting to the file at the same time and could end up
corrupting it. So, once flock() gains control over the file, all other functions that access
$datafile using the flock() method will now have to wait their turn.
Once the flock() function allows execution to proceed, the fwrite() function is called
to write the data in $data to $datafile, followed by a \n newline. This is to separate each
line from the next. Because the parameter of 'a' was used with fopen(), this data is
appended to the end of the file’s existing contents.
Finally, the lock is released using flock() with a parameter of LOCK_UN (for UNlock)
and the file is closed. At this point, the write has been made successfully and so a value of
1 is returned.
CAUTION The flock() function will not work on NFS and many other networked file systems, or
on FAT and its derivatives. Also, when using a multithreaded server API like ISAPI, you may
not be able to rely on flock() to protect files against other PHP scripts running in parallel
threads of the same server instance.
How to Use It
To add a post to your Guestbook, you just have to decide on the name of a file in which to store
the data and then pass that and the post details to the function PIPHP_PostToGuestBook(),
like this:
$name = 'F. Gump';
$email = '';
$website = '';
$message = 'Life is like a box of chocolates';
$result = PIPHP_PostToGuestBook('guestbook.txt', $name, $email,
$website, $message);
Of course, when handling user submitted data you will probably also want to sanitize
the input using other plug-ins from this book, such as Caps Control or Spell Check from
Chapter 3, or some of the Form and User Input plug-ins from Chapter 6, before saving data
to the Guestbook.
The Plug-in
function PIPHP_PostToGuestBook($datafile, $name, $email,

$website, $message)
{
$data = $name . '!1!' . $email . '!1!' . $website .
'!1!' . $message;
if (file_exists($datafile))
{
$lines = explode("\n",
rtrim(file_get_contents($datafile)));

if (in_array($data, $lines)) return 0;
}

×