<?php
session_start();
$_SESSION['ai'] = $_GET['ai'];

$ip = getIPAddress();  


// checking whether file exists or not 
  
$filename = 'dataFile.txt';

if (!file_exists($filename)) 
{
    $myfile = fopen("dataFile.txt", "a") or die("Unable to open file!");
	fclose($myfile);
}



// CHECK IF IP EXISTS OR NOT 

if(check_ip($ip))
{
	//if ip exists before then go to other url
	header("location: index.html");
}else
{
	$myfile = fopen("dataFile.txt", "a") or die("Unable to open file!");
	$txt = $ip."\n";
	fwrite($myfile, $txt);
	fclose($myfile);

//	echo "NOfound";

	// move to your choice of page
	header("location: index.html");
}


/*-----------------------*/
   /*--- FUNCTIONS ---*/
/*-----------------------*/


function check_ip($ip)
{	

	$myfile = fopen("dataFile.txt", "r") or die("Unable to open file!");

	// Output one line until end-of-file
	while(!feof($myfile)) 
	{
	  
	   $line = fgets($myfile);
	   if(preg_match('/'.$ip.'/', $line))
	   {
	   		return true;
	   }
	}
	fclose($myfile);

	return false;
}



 function getIPAddress() 
 {  
    //whether ip is from the share internet  
     if(!empty($_SERVER['HTTP_CLIENT_IP'])) {  
                $ip = $_SERVER['HTTP_CLIENT_IP'];  
        }  
    //whether ip is from the proxy  
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
     }  
	//whether ip is from the remote address  
    else{  
             $ip = $_SERVER['REMOTE_ADDR'];  
     }  
     return $ip;  
}  



?>
