Compare IP to SQL table values - php

I am capturing the visitors ip address during a form submit using the following.
$users_ip=$_SERVER['REMOTE_ADDR'];
What I would now like to do is see if this ip variable has been used before when submitting a comment, can anyone point me in the right direction?
Maybe a like SQL command?

Assuming you stored client ips in the table named: "ips" then use this:
$connection = mysql_connect($your_db_host, $your_user_account, $your_password);
$mysql_select_db($your_db_name);
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "select 1 from `ips` where `ip`='$ip'";
$sql_resource = mysql_query($sql);
$mysql_close($connection);
if($sql_resource && mysql_num_rows($sql_resource) > 0){
// your logic code if the ip existed in the db
echo 'The ip has been used before';
} else {
// code if the ip not existed in the db
echo 'The ip has not been used before yet';
}

There is a good tutorial explaining how to store IP addresses in MySQL. In short, convert them to long like suggested in this comment, then use simple SELECT statement to find it:
"SELECT COUNT(*) FROM comment WHERE ip = " . ip2long($_SERVER['REMOTE_ADDR'])

Related

Knowing the IP Address and check if it is registered in my database

I need to get the computer IP address and I need to check if that IP address is in my database. If it was, I need to display the name registered to that IP address that was in my database.
Actually I am confused because there were no error detected yet there were no output displayed.
Here's my code
<?php
$ipname = gethostbyname(trim(`hostname`));
$ip_query = "SELECT ip_address FROM table 5";
$ip_add = mysql_query($ip_query);
if ($ip_add === $ipname){
echo "{$ip_add['guest_name']}";
}
?>
the way you are retrieving the IP won't work in some cases, so first you need to get it using the function implemented here. for the query itself the query is retrieving the first 5 rows only, so you need to add "where" part so the query should be something like that $ip_query = "SELECT ip_address FROM table where ip = $ipname"; then after that you shouldn't compare the output of mysql_query, the output is a mysql resource you should use another function to get the result
$num_rows = mysql_num_rows($ip_add)
if ($num_rows>=1) {
$ip = mysql_result($ip_add,0,'ip_address');
// then compare the ip variable with the one you have from the function
}
Find, IP Address through given function. Check in query there itself. If ip address exist, Print guest name.
[NOTE: I Used YourTableName as table name. Put appropriate table name in query.]
<?php
$ipname = getIpAddress();
$query = mysql_query("SELECT guest_name FROM `YourTableName` WHERE ip_address = '$ipname'");
$countUser = mysql_num_rows($query);
if($countUser > 0){
while($row = mysql_fetch_array($query)){
echo "User Name: ".$row['guest_name']."<br>";
}
} else {
//Your Logic
}
function getIpAddress() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ips[count($ips) - 1]);
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
?>
NOTE: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

How to check if an IP is already stored in mysql?

I have this feedback form I made, but I need a bit of help. I want to stop people from posting feedbacks if they already did with the same ip, which is stored in a database. Here is the code:
<?php
if(isset($_POST['add'])){
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$ip = $_SERVER['REMOTE_ADDR'];
$datetime = date('Y-m-d H:i');
$checkIp = mysql_query("SELECT ip from comments WHERE ip = '$ip'");
if (mysql_num_rows($checkIp) > 0) {
echo "Only 1 feedback per IP allowed!";
$IP = mysql_fetch_array($checkIp);
print_r($IP);
}
if($name){
if($email){
if($comment){
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
mysql_query("INSERT INTO comments (id, name, email, comment, ip, datetime) VALUES ('','$name','$email','$comment','$ip','$datetime')");
}
else
echo "The email address is invalid!<br><br>";
}
else
echo "You haven't entered any comment!<br><br>";
}
else
echo "You haven't entered an email address!<br><br>";
}
else
echo "You haven't entered your name!<br><br>";
}
I tried to have a go myself, but failed (you can see at the top I tried some functions), can someone please tell me how to do it?
You should be using PDO or mysqli_ with prepared statements rather than mysql_ since its deprecated and due to be removed. Also, if you really want IP address to be unique in this table, you should set a unique constraint on the field.
But probably you could get this code working as far as this point (for about 90-98% of cases) simply by adding an exit; in the if-statement where you are checking the number of rows:
if (mysql_num_rows($checkIp) > 0) {
echo "Only 1 feedback per IP allowed!";
$IP = mysql_fetch_array($checkIp);
print_r($IP);
exit; //stop execution here so nothing else happens
}
The code will be open to SQL injection, however, if you continue with mysql_, and it won't be as straightforward and will leave open a technical possibility of somehow ending up with more than one of the same IP in the database.
For example, if two requests came in at once and both read the database as not having the IP yet, then both inserted. With a contraint in the table, that wouldn't happen because the database server would be managing the constraint itself.

Display dynamic PHP content based on IP address

In my MySQL database you login via the game and then type your username in on the site and see your stats. This is my information snippet from my API.
elseif ($_GET['task'] == 'login') {
$get_user = $_GET['user'];
$get_db = 'engine';
$result = mysql_query("SELECT * FROM $get_db WHERE name = '" . mysql_real_escape_string($get_user) . "'", $link);
while($data = mysql_fetch_array($result)) {
echo '{"task":"login","password":"'; echo $data['hash'];
echo '","lastip":"'; echo $data['lastip'];
echo '","timestamp":"'; echo $data['logindate'];
echo '"}';
}
}
I am trying to add a line of text under the search textbox on the homepage that will pop up if your IP recently logged into a server. It'll say "Hey, aren't you username?"
What type of code would be required to do this? I would need to call upon their IP, and search the database for all users who have authenticated with it, and then make sure to display the latest one based on their timestamp.
You can use both $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_X_FORWARDED_FOR'] to get the public IP and sometimes (with the second case) the private IP.
By the way, notice that old mysql_*() functions are deprecated as of PHP 5.5. You should use the mysqli or PDO_MySQL extensions.
$_SERVER['REMOTE_ADDR'] will give you the IP address of the person viewing the page.
From there you just need to compare it to the lastip field in your query.
$userIP = $_SERVER['REMOTE_ADDR'];
$query = "SELECT * FROM ".$get_db." WHERE lastip = ".$userIP." ORDER BY logindate DESC LIMIT 1";
Or something along those lines.
You could use the $_SERVER['REMOTE_ADDR'], which contains the IP of the viewer.
Then you could run
SELECT name FROM 'users' where users.known_ips LIKE '%$ip%' AND users.loggedin = 0 ORDER BY lastlogin DESC LIMIT 1;
('%' represents 0 or more characters. It's a wildcard.) And then you could use
mysqli_stmt_bind_results($ipquery,$name);
mysqli_stmt_fetch($ipquery);
# Now $name = first username found
This method will get their name if they have ever used that computer to log in.

using php to make a ip visit counter in mysql

I am a very novice programmer and am just beginning to use php.
I am using php to get the user ip store it in mysql. try inserting the ip to the mysql db. if it is already there then update the visit count. But none of my queries are working. It is returning that I am connected to my db
This is what i have so far:
$ipaddress = $_SERVER["REMOTE_ADDR"];
print "$ipaddress <br>";
$rv = mysqli_real_query("INSERT INTO visit ( ipaddress, count) VALUES ( '$ipaddress', 1)");
if ($rv === false){
mysqli_real_query($con,"UPDATE visit SET count=count+1
WHERE ipaddress = '$ipaddress'");
mysqli_close($con);
}
mysqli_close($rv);
$count = mysqli_real_query("SELECT count from visit where ipaddress = '$ipaddress'");
print "You have visited this site $count time(s)";
1.) Where's your $con for your first query in $rv?
2.) Your queries need backticks for reserved words such as count:
$rv = mysqli_real_query($con, "INSERT INTO `visit`(`ipaddress`, `count`) VALUES('$ipaddress', 1)");
3.) Your inside if statement will only fire if there is an error in your first line. This means you'll never actually UPDATE the count, unless something went wrong.
Suggestion 1: - Open up your table in phpmyadmin and insert a row in manually with your IP address and some random count number. Then work on being able to display the line You have visited this site x time(s). Once that is working, then work on inserting/updating your table.
Suggestion 2: You should do it the other way around. That is, check to see if the ip address exists in the table. If it does - update it. If it doesn't exist, then add a new row.
This is fine for practicing simple database connections, but a better way to do this would be to write a simple file to a /tmp/ folder and append 1 character. A single ASCII character is 1 byte, so the number of visits is simply the filesize of that ip file in bytes. Appending a single character and running a filesize check should have a lot less overhead than running database queries.
Example:
//Logging a Visit
$log_file = '/tmp/ip_'.$_SERVER['REMOTE_ADDR'];
$log = fopen($log_file, "a");
fwrite($log,'0');
fclose($log);
//Displaying Count
if(file_exists($log_file)){
$visits = filesize($log_file);
echo $log_file.' has visited the site '.$visits.' time'.($visits>1 ? 's':'');
}
else{
echo $log_file.' has not previously visited the site';
}
See here for an example of how I suggested this method to another user to block a bot that visited a site more than x number of allowed times: Number of page requests by any Bot in 5 secs
Also, just remember that with routers and NAT, an ip address does not guarantee a unique visitor, so IP address should not be relied on to identify a unique user in most situations.
Some problems:
You aren't escaping your SQL statement.
You close your connection (twice), and then never open it again when you are executing the SELECT statement.
You are not escaping your query arguments.
Fixing these issues, results in the following:
<?php
$con = mysqli_connect();
$ip = mysqli_real_escape_string($_SERVER["REMOTE_ADDR"]);
$q = 'INSERT INTO `visit` (`ipaddress`, `count`)';
$q .= 'VALUES ("'.$ip.'",1) ON DUPLICATE KEY UPDATE `count` = `count` + 1';
$result = mysqli_real_query($q);
if (!$result) {
echo mysqli_error();
}
$q = 'SELECT `count` FROM `visit` WHERE `ipaddress` = "'.$ip.'"';
$result = mysqli_real_query($q);
if (!$result) {
echo mysqli_error();
} else {
print "You have visited this site ".$result[0]."time(s)";
}
?>

finding out if two people hold the same ip address php and sql

Right, I have done a small amount of coding, but have yet to find out how to do the following.
If two users have the same IP address, to mark it through echo.
I wish to make it so that if($user222['current_ip'] (has the same as another user)); { //do action
but I can not find the code any where... does it exsist?
I'd be forever grateful for any help (if you can)
my codes are the following:
`$usersearch = mysql_query ("SELECT * FROM users WHERE online = 'Online'");
$user222 = mysql_fetch_array($usersearch);`
<? if ($user222['reg_ip'] == $user222['current_ip']) {
echo "<font color='green'><b>".$user222['current_ip']."</b></font>";
} else if ($user222['reg_ip'] != $user222['current_ip']) {
echo "<font color='orange'><b>".$user222['current_ip']."</b></font>"; } else //add new code here ?>
EDIT::: I am wanting to find out if two users are registered with the same IP address through SQL. If there is then to echo the reason.
The question is very vague, however the client IP address can be obtained in PHP like this:
$client_ip = $_SERVER["REMOTE_ADDR"];
http://php.net/manual/en/reserved.variables.server.php
You could use cookies if you want to figure out if users are different based upon their browsers. One user could use multiple browsers, though.
As anttix said, you can use "$_SERVER['REMOTE_ADDR']" to obtain the user IP address. You have to register in the MySQL database all the IP addresses, of course.
$result = mysql_query("
SELECT *
FROM users
WHERE
ip = '$_SERVER[REMOTE_ADDR]';
");
while ($row = mysql_fetch_array($result)) {
if ($_SERVER['REMOTE_ADDR'] == $row[ip]) {
// do something
}
}

Categories