Reading files line by line and checking the data

Hi, I am new to php and I am currently creating a system that should take the viewer’s IP, hash it, and then check it against a file called ips.txt to determine if they have visited the web page before.
Here is my code:
<?php
$unique = 1;
$ip = $_SERVER['REMOTE_ADDR'];
$hashed = md5($ip);
$visitors = fopen("ips.txt","r");
while(!feof($visitors))
{
if(fgets($visitors) == $hashed);
$unique = 0;
}
fclose($visitors);
echo $unique;
?>
Please bare in mind that if the user with an IP that has visited before it should return ‘0’ and if they are new it should return ‘1’, I know that this will not add new IPs to the file for later use but my code to do that works already.
Please could someone point out where I have gone wrong and help me fix it?
Thanks!

Although you should be doing this with a database, as it will be faster and less resource intensive, with more than 100 entries.

What your code is doing is to read in a section of the file, not a line, and test if it matches your ip string, which it won’t. Also you need to be aware of End of line characters \r & \n & \r\n (depending on the OS). Trim() will help you there.

To do it easily with a file (as long as the hashes are store on individual lines):

  • This can be optimized more, but written to allow for readability *
<?php

function uniqueVisit( string $ip):int {
	$ips = file_get_contents( 'ips.txt' );
	if( strpos( $ips, $ip) !== false){
		// Visited Before
		return 0;
	}else{
		// Not Visited Before
		return 1;
	}
}

$unique = uniqueVisit( $_SERVER['REMOTE_ADDR'] );
1 Like

Thanks a lot!
I will try this out and also look into databases, I have SQL ready to go so I’ll look at some tutorials of how to use it and that. Thanks again for your help, it means a lot!
Edit: I am using a UNIX OS to host so I will need \n

Sponsor our Newsletter | Privacy Policy | Terms of Service