Jump to content

Writing File -Help


simon66

Recommended Posts

Hi all,

 

This is my first php file im working on so bear with me.

 

What Im doing here is that I want my php script to add the users IP to a file without deleting the files inside of it and if the IP is already in the file then it wont add it

 

This is what I have to far

 

<?php
$ip = getenv("REMOTE_ADDR") ; 
$file = fopen("ip.txt", "w+");

fwrite($file, $ip);
fclose($file);
?>

 

the problem there is it will not add to the file, it will delete what ever is inside of the it and just add the new IP. Plus I still to add the search. If some one could help It would be amazing :)

 

Ill be looking around to see if I can do a search

Link to comment
https://forums.phpfreaks.com/topic/201329-writing-file-help/
Share on other sites

To use a flat file you could something like this:

$ip = getenv("REMOTE_ADDR");
$lines=file("./ip.txt");

while (list($key,$value) = each($lines)) {

$value=trim($value);

if($value==$ip){$found=1; break;}
}
	if(!$found)
	{
	$write="$ip\n";
	file_put_contents("./ip.txt",$write,FILE_APPEND);
	}

 

What we are doing is putting the ip.txt file into an array then looping with a while/list/each. We use that cause as the file gets larger its a hit to use a foreach loop as a copy is used but a while/list/each goes line by line through the original array. We break if we find a match otherwise if we didnt find a match we append the IP to the file.

 

 

HTH

Teamatomic

Link to comment
https://forums.phpfreaks.com/topic/201329-writing-file-help/#findComment-1056945
Share on other sites

Perhaps...

 

#######################################
# file_put_contents is PHP 5>
#
# this piece checks to see if that function exists
#	if NOT creates the function
#######################################

if (!function_exists('file_put_contents')) {
function file_put_contents($filename, $data) {
	$f = @fopen($filename, 'w');
	if (!$f) {
		return false;
	} else {
		$bytes = fwrite($f, $data);
		fclose($f);
		return $bytes;
	}
}
}

$file_name = "ip.txt";
$needle = getenv("REMOTE_ADDR");
if(($pos = strpos(file_get_contents($file_name), $needle))===false) {
file_put_contents($file_name, file_get_contents($file_name) . $needle . "\n");
}

 

N...

 

Link to comment
https://forums.phpfreaks.com/topic/201329-writing-file-help/#findComment-1056956
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.