Sorry if this has been asked before, but my search didn't yield much help. I'm having some issues incorporating the PHP built-in function 'ip2long' in my script. The input IP addresses are coming from a text file and the function is only picking up the last address on the list to do the conversion on. I'm running the script on a 32-bit machine if that gives a clue to the problem.
<?php
$text_file = 'ip.txt';
//begin reading text file
if (($file = fopen($text_file, "r")) !== FALSE) {
echo "Begin IP Convertion
";
while ($line = fgets($file)) {
echo "$line = " . ip2long($line) . "
";
}
} else {echo "No file found
";}
fclose($file);
?>
Here are the contents of the ip.txt file:
127.0.0.1
1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4
Result upon running the script:
# php ip.php
Begin IP Convertion
127.0.0.1
=
1.1.1.1
=
2.2.2.2
=
3.3.3.3
=
4.4.4.4 = 67372036
#
-Jon
You must remove the newlines from the string using something like trim
<?php
$text_file = 'ip.txt';
//begin reading text file
if (($file = fopen($text_file, "r")) !== FALSE) {
echo "Begin IP Convertion
";
while ($line = fgets($file)) {
echo trim($line) . " = " . ip2long(trim($line)) . "
";
}
} else {echo "No file found
";}
fclose($file);
?>