Reputation: 57
I have a script that I am working on in PHP that logs IP Address's of visters that go to that specific page. This is just a prototype. The script that I have concocted is working, but when it creates the TXT file containing the IP's it only does one line. How can I make it keep adding a line for every visitor regardless if they are a repeat visitor. I am not really sure how to go about that part, I am new to PHP.
Here is what I have so far:
<?PHP
$ip = getenv("REMOTE_ADDR");
$date = date("d") . " " . date("F") . " " . date("Y");
$intofile = $ip . "n" . $date;
$hfile = fopen("ip-address.txt", "w");
fwrite($hfile, $intofile);
fclose($hfile);
?>
<!DOCTYPE html>
<html language="en-us">
<head>
<title>IP Address Logging Software</title>
<link rel="stylesheet" type="text/css" href="Source/Stylesheet/DefaultPage.css" />
<link rel="stylesheet" type="text/css" href="Source/Stylesheet/DefaultPage.css" />
<link rel="stylesheet" type="text/css" href="Source/Stylesheet/DefaultPage.css" />
<script type="text/javascript" src="Source/Javascript/DefaultScript.css"></script>
<script type="text/javascript" src="Source/Javascript/DefaultScript.css"></script>
<script type="text/javascript" src="Source/Javascript/DefaultScript.css"></script>
</head>
<body language="en-us">
<?PHP
$ip=$_SERVER['REMOTE_ADDR'];
echo "<strong>Your IP Address <em>$ip</em> Has Been Logged</strong>";
?>
</body>
</html>
Upvotes: 1
Views: 5777
Reputation: 176
Alternatively use file_put_contents (http://php.net/manual/en/function.file-put-contents.php). Its basically a helper function that does the same as calling fopen()
,fwrite()
, and fclose()
.
And to make sure that it appends the content just add the FILE_APPEND
flag:
file_put_contents('file.txt', 'Hello World', FILE_APPEND);
Upvotes: 0
Reputation: 24661
$hfile = fopen("ip-address.txt", "w");
Refer to the manual for fopen
:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Everytime you open the file it is being truncated. Use the 'a+'
instead, or another one that will open the file and append, rather than delete what's already there.
Upvotes: 2