Your variables were not properly set and were done the other way around.
Quick note: wb
means to write binary. Unless that is not your intention, I suggest you use only w
.
Your filename ending in .txt
is text, therefore use the w
switch. That will overwrite previous content.
You had:
$_POST['IP']=$ip;
unlink('boot_ip.txt');
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/boot/boot_ip.txt","wb");
fwrite($fp,$IP);
fclose($fp);
This => $_POST['IP']=$ip;
where it should be $ip=$_POST['IP'];
and this fwrite($fp,$IP);
should be fwrite($fp,$ip);
You had the $IP
in uppercase when it should be in lowercase as you declared in your variable.
NOTE: The unlink
part of the code may need to reflect your folder's place on your server.
However, I suggest you do not use unlink
because using it will throw an error right away, because the file may not be found to begin with, since it would have already been unlinked.
You can either not use it, or use an if
statement. See my example following my code below.
Plus, using the w
switch, will automatically overwrite previously written content.
If you need to append/add to the file, then you will need to use the a
or a+
switch.
If that is the case, then you will need to use the following:
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/boot/boot_ip.txt","a");
fwrite($fp,$ip . "\n");
Reformatted (tested and working)
$ip=$_POST['IP'];
unlink('boot_ip.txt');
// use the one below here
// unlink($_SERVER['DOCUMENT_ROOT'] . "/boot/boot_ip.txt");
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/boot/boot_ip.txt","wb");
fwrite($fp,$ip);
fclose($fp);
Using the following form:
<form action="handler.php" method="post">
<input type="text" name="IP">
<input type="submit" value="Submit">
</form>
Using an if
statement method.
$ip=$_POST['IP'];
if(!file_exists($_SERVER['DOCUMENT_ROOT'] . "/boot/boot_ip.txt")) {
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/boot/boot_ip.txt","wb");
fwrite($fp,$ip);
fclose($fp);
}
$ip
!==$IP
and you shouldn't use$_POST['something'] = $something
'wb'
stands for "write binary" (think FTP transfer modes, binary vs text).