Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving current ip addresses in mysql table

Tags:

php

mysql

web

I am looking for a good way, to show how much people are accessing my website currently (live).

I figured out, that it would be probably the easiest way, when i save the ip address of the person, that accessing my server/site, in an mysql table.

so what i probably have to do is:

creating an well configured mysql table

adding the feature (i guess in php) of saving the ip address

adding the feature of deleting the ip address, if it isn't needed any longer

making the process realtime or close to realtime

Can somebody help me?

like image 619
user1644622 Avatar asked Jan 27 '26 23:01

user1644622


1 Answers

Here is a quick example of how you might go about getting the real IP address of a client and then storing and retrieving its value from the mysql DB

//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
  $ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
  $ip=$_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);
//The $ip would now look something like: 1073732954

Now that you have the real IP address of the client converted to the INT format, you can write it into the DB as you normally would

$sql = "INSERT INTO user(ip) VALUES('$ip')";
$dbQuery = mysql_query($sql,$dbLink);

More on this link: Best way to store IP addresses in MySQL

additional information: to make you code safe from SQL Injection. Use PDO or MYSQLI

Example of using PDO extension:

<?php

    $stmt = $dbh->prepare("INSERT INTO user(ip) VALUES(?)");
    $stmt->bindParam(1, $ip);

    $stmt->execute();
?>
like image 57
John Woo Avatar answered Jan 30 '26 16:01

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!