DJ Mike's Tutorials: PHP


< ^ >

Working With Files

Reading & Writing A File

Text Counter and Logger

Counter

To make a counter, I first create a file to be my database and name it "files_08_a.log". It could be a .txt file but I name it .log so I know what it is by the extension. For PHP to be able to write to it, permissions must be set to 666. The log file will consist of just a single line containing the count..

After opening the log file in read only mode, I use fgets() to read the contents and assign it to a variable. fgets() has one required argument: a file resource, an optional argument: length in bytes and returns a string variable. If a no length argument is supplied, the string returned will stop at 1k (1024 bytes) in length or the end of the line, which ever comes first. If a length is supplied, reading stops at lengh-1 or the end of the line. If an error occurs, FALSE is returned.

When I tried to add 1 to the variable at this point, I ran into a problem. When you use fgets(), the variable returned is a string variable, not a numeric variable so I had to use intval() to make it into a numeric before adding 1 to it. After I have the updated count, I close the file and reopen it in write only mode.

At this point, you might ask, "Why not just open the log file in read/write mode and read it and write it in one step instead of opening it twice?" The answer is, I tried that and it didn't work. When you open it in read/write mode, the first thing PHP does, is delete the contents of the file so after you add one, the contents of the log is always 1.

With the file open in write only mode, I can overwrite the old count with fwrite(). fwrite has two arguments, a file resource and the string to write in this format:

fwrite($file_resource, "$string"); 

When you are finished writing to the file, close it with fclose().

<? 
$temp 
fopen("files/files_08_a.log""r"); 
$count fgets($temp); 
$count intval($count); 
$count $count+1
fwrite($temp"$count"); 
fclose($temp); 
$temp fopen("files/files_08_a.log""w"); 
fwrite($temp"$count"); 
fclose($temp); 
?>


The contents of the log file can be put anywhere you want with file_get_contents().

<center>Viewed <?  file_get_contents("files/files_08_a.log"); echo ""?> times</center>

Viewed 2267 times

Logger

If you want some more information of the viewers of your page than how many times it has been viewed, you can make a logger. For this demonstration, I will log information on the last five page views. To do so will take several steps:

  1. Grab the variables the server variables that you'll want to use later.

    <?
    # get variables
    $agent strip_tags($_SERVER['HTTP_USER_AGENT']);
    $IP $_SERVER['REMOTE_ADDR'];
    $host strip_tags(gethostbyaddr($IP));
    $self $_SERVER['PHP_SELF'];
    $ref strip_tags($_SERVER[HTTP_REFERER]);

    # open & write to log
    $array file("files_08_b.log");
    $count count($array);
    if ( 
    $count 4)
    {
    # $old = array_shift($array);
    array_shift($array);
    }

    $time date"m/d/y G.i:s"time() );
    $new "<li><b>Time:</b> $time<br /><b>IP:</b> $IP<br /><b>Host:</b> $host<br /><b>Agent:</b> $agent<br /><b>Viewed</b> <a href=\"http://$_SERVER[HTTP_HOST]$self\">$self</a><br /><b>Came from:</b> <a href=\"$ref\">$ref</a>\n";

    array_push($array"$new");

    $log_02 fopen("files_08_b.log""w");
    foreach( 
    $array as $temp)
    fwrite$log_02"$temp); }
    fclose($log_02);
    ?>


    (You could use the server variables directly in your script. I do it this way because I make less errors this way.)
  2. Read the log file as an array.
    To keep each entry separate, each entry will each be added to the log page as a single line. Each line will be a member of the array. To read a file as an array, use file() in this format:

    $array_name = file("file_name");

  3. Count how many members are in the array.
    This is done with count() in this format:

    $variable = count($array_name);

  4. If there are more than 4 members, delete the top entry to make room for the new one. This can be done with arrey_shift(). arrey_shift() removes and returns the top member of an array in this format:

    $top_member = array_shift($array);

    Since I don't need the top member returned, I use it like this instead:

    array_shift($array);

  5. Compile the new entry into one long string ending in a newline character (\n).
    If you forget the \n), file() may not separate each entry the way that you want it to. If you use your Return key in the middle of the string, each entry may end up being broken into more than one entry
  6. Append it to the array of entries with array_push(). array_push() adds a member to the bottom of the stack of an array in this format:

    array_push($array_name, "$new_member");

  7. Open the log file in write only mode.
  8. Overwrite the old list with the new one.
    Since all your new log entries are an array instead of a single variable, you have to add them one by une with a foreach loop.

    foreach( $array as $temp)
    { fwrite( $log_02, "$temp" ); }


  9. Close the file
<?
# get variables
$agent strip_tags($_SERVER['HTTP_USER_AGENT']);
$IP strip_tags($_SERVER['REMOTE_ADDR']);
$host gethostbyaddr($IP);
$self $_SERVER['PHP_SELF'];
$ref strip_tags($_SERVER[HTTP_REFERER]);

# open & write to log
$array file("files/files_08_b.log");
$count count($array);
if ( 
$count 4)
{
# $old = array_shift($array);
array_shift($array);
}

$time date"m/d/y G.i:s"time() );
$new "<li><b>Time:</b> $time<br /><b>IP:</b> $IP<br /><b>Host:</b> $host<br /><b>Agent:</b> $agent<br /><b>Viewed</b> <a href=\"http://$_SERVER[HTTP_HOST]$self\">$self</a><br /><b>Came from:</b> <a href=\"$ref\">$ref</a>\n";

array_push($array"$new");

$log_02 fopen("files/files_08_b.log""w");
foreach( 
$array as $temp)
fwrite$log_02"$temp); }
fclose($log_02);
?>

IMPORTANT Do not use include() to put the data on your web page. Use file_get_contents() instead. Hackers can replace their browser information with PHP code and if you use include() the logged code will be live and they can use that to highjack your web site. I used strip_tags() in the example above to prevent that but you should still never include a file that can be modified by someone else

<center>Last 5 visiters</center>
<ol>
<?
2267 
file_get_contents("files/files_08_b.log");
echo 
"";
?>
</ol>

Last 5 visiters
  1. Time: 05/18/12 17.48:05
    IP: 199.21.99.93
    Host: spider-199-21-99-93.yandex.com
    Agent: Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)
    Viewed /mike/tutorials/php/files_08.php/mod...ules/vwar/admin/files_01.php
    Came from:
  2. Time: 05/18/12 18.00:27
    IP: 199.21.99.93
    Host: spider-199-21-99-93.yandex.com
    Agent: Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)
    Viewed /mike/tutorials/php/files_08.php/mod...ules/modules/vwar/convert/index.html
    Came from:
  3. Time: 05/18/12 18.17:46
    IP: 199.21.99.93
    Host: spider-199-21-99-93.yandex.com
    Agent: Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)
    Viewed /mike/tutorials/php/files_08.php/mod...nver...ules/vwar/admin/modules/vwar/convert/mvcw_conver.php
    Came from:
  4. Time: 05/18/12 18.41:42
    IP: 199.21.99.93
    Host: spider-199-21-99-93.yandex.com
    Agent: Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)
    Viewed /mike/tutorials/php/files_08.php/modules/vwar/convert/arrays_using_01.php/modules/vwar/admin/files_01.php
    Came from:
  5. Time: 05/18/12 18.51:41
    IP: 38.107.179.219
    Host: 38.107.179.219
    Agent: CCBot/1.0 (+http://www.commoncrawl.org/bot.html)
    Viewed /mike/tutorials/php/files_08.php
    Came from:

After you learn how to create images, you can make an image based counter/logger.

< ^ >


Was this webpage useful to you? You can support this website by donating.


Created by DJ Mike from Santa Barbara

DJ Mike


<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>