I have a rating script that logs users' IPs so they can't rate the file more than once. However, every time I rate the file to test it, my $ip changes with the ip2long() function. What's up? Here's my code:
<?php
require('connect.php');
$sheetID = $_GET["id"];
$rating = $_GET["rating"];
$ip= $_SERVER['REMOTE_ADDR'];
$ip = ip2long($ip);
$checkIPQuery = mysql_query("SELECT * FROM ratings WHERE sheetID = '$sheetID' and INET_NTOA(ip) = '$ip'");
$doesIPExist = mysql_num_rows($checkIPQuery);
if ($doesIPExist == 0) {
mysql_query("INSERT INTO ratings (sheetID, rating, ip) VALUES ($sheetID, $rating, $ip)");
echo " $ip
<script>setTimeout(function(){location.href = '../sheets.php?id=$sheetID'},1);</script>";
}
else
echo 'You have already rated this image!';
?>
And then for the check if the user has rated script:
$id = $_GET['id'];
$ip=$_SERVER['REMOTE_ADDR'];
$ip = ip2long($ip);
$checkIPQuery = mysql_query("SELECT * FROM ratings WHERE sheetID = '$id' and INET_NTOA(ip) = '$ip'");
$doesIPExist = mysql_num_rows($checkIPQuery);
Here's what I've done:
Any help would be appreciated. Thanks!
Edit: These scripts work fine if I set the $ip to 3 for example.
After reading the comments and a little research I found the answer and it is simple.
On 32-bit systems ip2long()
returns negative and positive integers but INET_NTOA()
only works with positive integers. So you have two options to fix that:
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));
... AND ip = " . ip2long($_SERVER['REMOTE_ADDR']) . " ...
You can verify this fact this way:
$ip = $_SERVER['REMOTE_ADDR'];
$int = ip2long($ip);
var_dump($ip, $int, sprintf('%u', $int));
This produces the following output:
string '192.168.1.120' (length=13)
int -1062731400
string '3232235896' (length=10)
Then go to MySQL:
mysql> SELECT '192.168.1.120', INET_NTOA(-1062731400), INET_NTOA(3232235896)
+---------------+------------------------+-----------------------+
| 192.168.1.120 | INET_NTOA(-1062731400) | INET_NTOA(3232235896) |
+---------------+------------------------+-----------------------+
| 192.168.1.120 | NULL | 192.168.1.120 |
+---------------+------------------------+-----------------------+
1 row in set (0.00 sec)