Pages

Tuesday, 10 July 2012

PHP OPEN READ FILES


Save IP address and referrer of our page

Let's suppose we want to record the IP address and Referrer of all visitors to our page. The script bellow may be placed within the code of our page and it will create two files to store both data: "ips_file.txt" to store IP addresses and "ref_file.txt" to store referrers. Additionally, this script may be use to track number of times users from a specific IP address visits our page.
To use this code written permission must be available in the directory containing the file with this code (in order to create the files).
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?
// save ip
$ip=$_SERVER["REMOTE_ADDR"];
if ($ip!=""){
        $ipfile= "ips_file.txt";
        $allips =  file_get_contents ($ipfile);
         if (strpos($allips," $ip ")>0){
                  $allips = preg_replace ("/ $ip /"," $ip x",$allips);
                  $tempvar= fopen($ipfile, "w");
                  fwrite ($tempvar, $allips);
                  fclose($tempvar);
       }else{
                  $tempvar = fopen($ipfile, "a");
                  fwrite ($tempvar, " $ip x\n");
                  fclose($tempvar);
        }
}

// save referrer
$ref=$_SERVER["HTTP_REFERER"];
if (strpos($ref,"mydomain.com")==0 and $ref!=""){
        $refffile= "ref_file.txt";
        $tempvar = fopen($refffile, "a");
        fwrite ($tempvar, $ref."\n");
        fclose($tempvar);
}
?>
Lines 2-13: saves the IP addresses to the file "ips_file.txt". Check the typical content of this file below.
Line 3: Get the IP address of visitors and stores the value in variable $ip.
Line 4: If $ip has been obtained, lines 5-16 are processed.
Line 5: Defines the name of the file containing the IP addresses.
Line 6: Reads the content of the file to variable 
$allips.
Line 7: Checks whether the IP of visitor has been already save in the file. If so, lines 8-11 are processed. If not, lines 13-15 are processed.
Lines 8-11:  In line 8, a replacement in the variable containing the content of the file "ips_file.txt" is performed (variable $allips). This replacement will place a “x” after the IP address already recorded in the variable. In lines 13-15 the file "ips_file.txt" is overwritten with the content in the variable.
The typical content of file "ips_file.txt" will be the one bellow, where the number of "x" after each IP indicates number of visits from that specific IP to our file.
ips_file.txt
 150.150.150.150 x
 150.150.150.151 xxxxxxx
 150.150.150.152 xxx
 150.150.150.153 x
 150.150.150.154 xxxxxxxxx
Lines 19-26: saves the referrer to the file "ref_file.txt". Check the typical content of this file below.
Line 20: Get the referrer of visitor and stores the value in variable $ref.
Line 21: The following are checked:  
Check whether the referrer site is our own site (whether "mydomain.com" is within the variable $ref); if so, next three lines are not processed.
Check whether the value of $ref is different to "" (so whether a value exists); if  no value is contained in the variable $ref, next three lines are not processed.
Line 22-25: the value at $ref is appended to file ref_file.txt.

The typical content of file "ref_file.txt" will be the one bellow:
ref_file.txt
http://search.yahoo.com/search?p=myquery
http://www.myreferrer.com/main.html
http://search.yahoo.com/search?p=myquery2
http://www.google.com/search?q=a+diferent+query
http://www.myreferrer2.com/dir/file33.html

Calender


year 2012 

January
1234567
891011121314
15161718192021
22232425262728
293031    
February
   1234
567891011
12131415161718
19202122232425
26272829   
March
    123
45678910
11121314151617
18192021222324
25262728293031
April
1234567
891011121314
15161718192021
22232425262728
2930     
May
  12345
6789101112
13141516171819
20212223242526
2728293031  
June
     12
3456789
10111213141516
17181920212223
24252627282930
July
1234567
891011121314
15161718192021
22232425262728
293031    
August
   1234
567891011
12131415161718
19202122232425
262728293031 
September
      1
2345678
9101112131415
16171819202122
23242526272829
30      
October
 123456
78910111213
14151617181920
21222324252627
28293031   
November
    123
45678910
11121314151617
18192021222324
252627282930 
December
      1
2345678
9101112131415
16171819202122
23242526272829
3031     

PHP simple user counter


PHP: Simple Active Users Counter

Simple Active Users Counter is a service to record and show number of recent active/online users.
Simple Active Users Counter does not use databases. The information is stored in files, but uses a different strategy to the one in other counters: when a user visits a page in our website, a file is created within a "counters" folder. The name of the file is the IP address of the user. For each user a new file is created, and the modification date of the file will correspond to the most recent activity of that specific user in the website. In case the visitor is not a new one, the file with that specific IP address will be overwritten, so a new 'most recent activity' will be recorded (which corresponds to the last modification date of the file). Recording user's last activity does not require reading information stored in a database or text file.
When counting number of recent visitors, all files in the "counters" folder are checked. In case the file has been created recently (for example in the last 5 minutes; this parameter is customizable) the file will be accounted as an active/online user. On the contrary, if the file is older, it will be deleted.
The procedure described for our Active Users Counter allows recording last activity of users without requiring reading the information in the database. Consequently, the webmaster may record information in all pages in the website, but the number of active users may be shown only in main page or in a limited number of pages, so that the computing and read/write activity will be limited to pages showing the number of active users.
As a consequence, Simple Active Users Counter may be consider as a simple (no databases) and fast (mostly for pages recording active users but not showing their number) service, but also a limited one(only active/online visitors are shown). Webmasters must decide whether showing number of active users is good enough for their websites. If so, this service is a good alternative.

Requeriments and code

To run this service, the following are required:
  • folder must be created to store temporal files.
    In the code bellow, a random string is included in the name of the folder.
    You may create a folder name "users_dwjBDKk67z" in the main directory of your site, or choose a different name. 
  • A copy of file "active_users_record.php" (bellow) must be copied to the server.
    Our suggestion is to copy it to main directory of your site.
  • A copy of file "active_users.php" (bellow) must be also copied to the server.
    Again, our suggestion is to copy it to main directory of your site.
  • Code to be included in your pages: 
    • In all PHP files you want to record users (but you do not want to show their number), the following code must be included.
      <? include($_SERVER["DOCUMENT_ROOT"]."/active_users_record.php); ?>
    • In all PHP files you want to record and show number of users, the following code must be included.
      <? include($_SERVER["DOCUMENT_ROOT"]."/active_users.php); ?>
    • The code bellow explains step by step the behaviour of the script.
      The code is totally functional, and in same places alternative options are shown (one of them is activated).
Code:
File 1:
active_users_record.php
<?

// ###############  SET UP THE VARIABLES  ########################################

// FOLDER USED TO STORE TEMPORAL FILES
//    IMPORTANT: the folder must have proper permissions to allow writing files
//    The name of the temporal files contains the IP address of the user
//    ($_SERVER["DOCUMENT_ROOT"] is the root folder for the website)
$folder=$_SERVER["DOCUMENT_ROOT"]."/users_dwjBDKk67z/";

// ###############  THE WORKING PART OF THE SCRIPT ##############################

// DO NOT SHOW ERRORS TO VISITORS (just in case)
error_reporting(0);

// GET IP ADDRESS OF USER (a function in the bottom is used)
$ip=getIP();

// REGISTER THE USER
//      A file will be created. The name of the file will contain the IP of the user.
//      In case the file already exists, it will be overwritted.
//      The creation time of the file will indicate how long ago the user
//              with this IP visited a page containing this active users counter
        // OPTION 1, for PHP4 or superior
        $cf = fopen($folder.$ip, "w");
        fwrite($cf, "");
        fclose($cf);
        // OPTION 2, for PHP5 or superior
        // file_put_contents ($folder."$ip.txt", "0");

// ########################  FUNCTIONS  #########################################
// funtion getIP will be used to get IP address of visitor
function getIP() {
        // Option 1 to get the IP address of visitor
        //      if a value for $_SERVER['HTTP_X_FORWARDED_FOR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
                return $ip;
        }
        // Option 2 to get the IP address of visitor
        //      if a value for $_SERVER['REMOTE_ADDR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
                return $ip;
        }
        // IP has not been obtained, so a default IP is returned
        //      The default value will be used very few times, so
        return "0.0.0.0";
}

?>
File2:
active_users.php
<?

// ###############  SET UP THE VARIABLES  ########################################

// FOLDER USED TO STORE TEMPORAL FILES
//    IMPORTANT: the folder must have proper permissions to allow writing files
//    The name of the temporal files contains the IP address of the user
//    ($_SERVER["DOCUMENT_ROOT"] is the root folder for the website)
$folder=$_SERVER["DOCUMENT_ROOT"]."/users_dwjBDKk67z/";

// TIME SINCE LAST ACTIVITY OF AN USERS TO BE CONSIDERED NON-ACTIVE
$timeold=300;   // seconds

// ###############  THE WORKING PART OF THE SCRIPT ##############################

// DO NOT SHOW ERRORS TO VISITORS (just in case)
error_reporting(0);

// GET ACTUAL TIME
$actualtime=date("U");   // seconds since January 1st, 1970.

// GET IP ADDRESS OF USER (a function in the bottom is used)
$ip=getIP();

// REGISTER THE USER
//      A file will be created. The name of the file will contain the IP of the user.
//      In case the file already exists, it will be overwritted.
//      The creation time of the file will indicate how long ago the user
//              with this IP visited a page containing this active users counter
        // OPTION 1, for PHP4 or superior
        $cf = fopen($folder.$ip, "w");
        fwrite($cf, "");
        fclose($cf);
        // OPTION 2, for PHP5 or superior
        // file_put_contents ($folder."$ip.txt", "0");

// COUNT NUMBER OF ACTIVE USERS
//      All files within folder $folder will be checked
//      Files $timeold seconds old (defined above) will be deleted
//      Files created up to $timeold seconds ago will be accounted as active users

        // a counter; no users at this moment
        $counter=0;
        // get the list of files within $folder
        $dir = dir($folder);
        // check all files one by one (variable $temp will be the name of each file)
        while($temp = $dir->read()){
                // the ones bellow are not files, so continue to next $temp
                if ($temp=="." or $temp==".."){continue;}
                // For real files, get the last modification time
                //   (number of seconds since January 1st, 1970)
                //    and save the data to variable $filecreatedtime
                $filecreatedtime=date("U", filemtime($folder.$temp));
                // check whether the file is $timeold seconds old
                if ($actualtime>($filecreatedtime+$timeold)){
                        // the file IS old, so delete it
                        unlink ($folder.$temp);                                                                   //
                }else{
                        // the file IS NOT old, so an active user will be accounted
                        $counter++;
        }
}
// DISPLAY NUMBER OF ACTIVE USERS
        // Option 1  (displays only the number of active users)
        //print "Users online: $counter";
        // Option 2  (displays number of active users, and defines how old an active user is in seconds).
        // print "Users online: $counter (in last $timeold seconds)";
        // Option 3  (displays number of active users, and defines how old an active user is in minutes).
        $minutes=round($timeold/60);
        print "Users online: $counter (in last $minutes minutes)";

// ########################  FUNCTIONS  #########################################
// funtion getIP will be used to get IP address of visitor
function getIP() {
        // Option 1 to get the IP address of visitor
        //      if a value for $_SERVER['HTTP_X_FORWARDED_FOR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
                return $ip;
        }
        // Option 2 to get the IP address of visitor
        //      if a value for $_SERVER['REMOTE_ADDR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
                return $ip;
        }
        // IP has not been obtained, so a default IP is returned
        //      The default value will be used very few times, so
        return "0.0.0.0";
}

?>
 

PHP hit counter


Simple Hit counter

A hit counter will let us know how many times a page is accessed. In case one visitors loads the page several times, the hit counter will increase several times (but this is likely to happen only a few times).

The code for the hit counter bellow will save the number of hits in a file named counter.txt (the name of this file may be changed). Each time the page is loaded, the file will be read, the number will be increased by one and the new number will be saved to the same file.

counter.php
<?php

//The file where number of hits will be saved; name may be changed; p.e. "/counter_files/counter1.txt"
$counterfile = "counter.txt";

// Opening the file; number of hit is stored in variable $hits
$fp = fopen($counterfile,"r");
$hits = fgets($fp,100);
fclose($fp);

//increading number of hits
$hits++;

//saving number of hits
$fp = fopen($counterfile,"w");
fputs($fp, 
$hits);
fclose($fp);

//printing  hits; you may remove next line (and keep the counter only for your records)
print 
$hits;

?>

To use this code, copy it to your page in the exact position where you want to show number of hits. If your page is a ".html" page, change the extension to ".php". Them, visit your page. In the first visit, you will get a couple of errors (the file where number of hits are recorded does not exists, so some errors will be shown in the page). Reload the page and you will see no errors. The hit counter will be working.

In case you want to use different hit counters for different pages, chage name of $counterfile for each page (p.e.: counter1.txt, counter2.txt, etc).


PHP form to mail tutorial


Form to mail

Would you like to get on your email all the information included in a form?
  • First of all you need a form, as for example the one in the table:

form.html
<FORM ACTION="formtomail.php" METHOD=post><!-- Your fields here -->
<INPUT TYPE=submit value="Submit">
</FORM>
    The Form Action must be directed to the PHP script bellow.
  • Second: you need the php script (copy the information in the table to a text file
  • and save the file as "formtomail.php" in your server).
formtomail.php
<?
if ($_POST){
      // posted information is added to variable message
      $
message="";
      foreach ($_POST as $formfieldname => $formfieldvalue){
            $
message.="$formfieldname \n $formfieldvalue\n\n";     // 
      }
     // send email with information from the form to
      
mail("webmaster@mysite.com","Form to Mail", $message,"From: <webmaster@mysite.com>\nContent-Type: text/plain");
      print "The information has been send to webmaster";
}else{
      print "No information has been posted";
}

?>

You need to customize the script: substitute red text in the script by your email.

This scripts assumes you have no restrictions to use mail commnad.

Tutorials on php


PHP Contact form

It is not a good idea to place a contact email in your web. Someone may use a robot to find your email and send spam. Instead, it is recommended to use a contact form. Alternatively, you may use javascript to hide your complete email (info).

You will find bellow a copy and paste contact form. You just need to copy the code to a file named contact_form.php, change emails in red, and place it in your site. Them add a link to the contact form in your regular pages.


contact_form.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html><head><title>Contact Form</title></head>
<body bgcolor=FFFFFF>

<center><p><center>
<H1>Suggestions/Questions about mysite.com</h1>
<table><tr><td>

<?
$text=$_POST["text"];$email=strtolower($_POST["email"]);
if (strpos($email,"@")==0 or strpos($email,".")==0){$email="";}
if ($email!="" and $text!=""){
   $message="$email\n\n$text";
   mail("webmaster@mysite.com","Contact form", $message,"From: <webmaster@mysite.com>\nContent-Type: text/plain");
   print "<center>Thanks for your Suggestion/Question<p><a href=/>Home Page</a></center>";
}else{
?>

<form action=<? print $_SERVER["PHP_SELF"]; ?> method=post>
<p>Your contact email:<br>
<INPUT NAME="email" SIZE="35" MAXLENGTH="65">
<BR>Your text:<br><TEXTAREA name=text cols=40 rows=5><? print $text; ?></TEXTAREA>
<br><INPUT TYPE="SUBMIT" NAME=submit VALUE=Submit>
</form>

<? } ?>

</td></tr></table>
</center></body></html>

Lines 1-6: Just page title and headings

Lines 8-17: php code

Line 9: Text introduced by user is saved to variable $text.
Line 10: email is saved to variable $email. By using strtolower, we will get the email in lower case.
Line 11: It is checked whether email is correct (simple checking). The command strpos is used to check position of "@" and "." within $email. If position is "0", $email is not correct and email information is removed (is set to "").
Line 12: If value of $email or $text is not null, lines 13 to 15 are executed. If not, the form in lines 20-25 is displayed.
Line 13: A new variable named is created which contects the email value and text of user. The code "\n\n" means we are separating email and text with two line breaks.
Line 14: The command mail is used to send email.
Line 15: A "Thanks you" message is shown.
Lines 20-25: If message is not send (for example when getting to the page from a link), the form is displayed.

Line 23: In case a user has introduced a message in the textbox, but has forgotten to include email, as $email="", mail is not send to webmaster, and the form is displayed. In this case, the code "<? print $text; ?>" is used to include the message in the textbox.
Lines 29-30: Finishing the page.

PHP Contact form (version 2)

The contact form above may be use by spanners to send you ads and other span message. The new version bellow includes a bit of code (in magenta) to avoid this fraudulent usage.


contact_form.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html><head><title>Contact Form</title></head>
<body bgcolor=FFFFFF>

<center><p><center>
<H1>Suggestions/Questions about mysite.com</h1>
<table><tr><td>

<?
$text=$_POST["text"];$email=strtolower($_POST["email"]);
if (strpos($email,"@")==0 or strpos($email,".")==0){$email="";}
if ($email!="" and $text!=""){
   $jcontrol=$_POST["javascriptcontrol"];
   if ($jcontrol=="") {die("Error: This service does not believes you have not visited the website with a regular browser.");}
   $message="$email\n\n$text";
   mail("webmaster@mysite.com","Contact form", $message,"From: <webmaster@mysite.com>\nContent-Type: text/plain");
   print "<center>Thanks for your Suggestion/Question<p><a href=/>Home Page</a></center>";
}else{
?>

<form name=AA action=<? print $_SERVER["PHP_SELF"]; ?> method=post>
<p>Your contact email:<br>
<INPUT NAME="email" TYPE=text SIZE="35" MAXLENGTH="65" onchange="document.AA.javascriptcontrol.value='dd';">
<INPUT NAME="javascriptcontrol" TYPE=hidden value="">
<BR>Your text:<br><TEXTAREA name=text cols=40 rows=5><? print $text; ?></TEXTAREA>
<br><INPUT TYPE="SUBMIT" NAME=submit VALUE=Submit>
</form>

<? } ?>

</td></tr></table>
</center></body></html>

How it works:
When email is included in the form, a javascript code (in line 23) will add the value "dd" to the hidden variable "javascriptcontrol" (in line 24). In case javascript is not available in the browser, this change will not happen (for example when a robot visits our page, fills the form and submits it without using javascript). In lines 13 and 14 it is checked whether the value for the variable "javascriptcontrol" exists. If there is no value for this variable, an error is reported (and no email is send).

Display contact email by using javascript

The code bellow may be used to display a link for contact, but avoiding robots from obtaining the address.
This is not a PHP program.

javascript code Output example
<script language="JavaScript" type="text/javascript">
 document.write("<A HREF=\'mailto:myname");
 document.write("@");
 document.write("mydomain.com\'>");
 document.write("Contact email");
 document.write("</A>");
</script> 
Contact email 

How it works:

The link which includes the contact address is printed out only when javascript is available. Consequently, a robot will not find the email. Just modify the email in red and copy the code to the exact location in the page you want the contact link to be displayed.