saving IP address in mysql database - php

I have a problem with saving the IP address into DataBase
This is how i get the ip:
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
That is my DB Table creation php file
$sql = "CREATE TABLE users (".
"ID INT NOT NULL AUTO_INCREMENT,".
"Guest VARCHAR(60) COLLATE utf16_general_ci,".
"IPAdd INT UNSIGNED NULL DEFAULT NULL,".
"PRIMARY KEY(ID));";
$retval = mysql_query( $sql, $conn );
End this is how i save the Users IP
require("DBConnection.php");
require("getIP.php");
echo $user_ip."<br>";
if ($user_ip === '::1'){
$user_ip = '127.0.0.1';
}
$user_ip = ip2long ($user_ip);
echo $user_ip."<br>";
//Проверява ме за вече съществъващ гост
$selectData = mysql_query("SELECT * FROM users");
if (!$selectData )
{
die('Could not get data: ' . mysql_error());
}
else {
$i = 1; // index za poreden nomer na potrebitelq.
$guest = 'Guest'.$i;
while ($row = mysql_fetch_array($selectData) )
{
if($row[1] == $guest && $row[2] != $user_ip )
{
$i++;
$guest = 'Guest'.$i;
}
}
$sql = "INSERT INTO `cssgendb`.`users` (`ID`, `Guest`, 'IPAdd')
VALUES ('0', '$guest', '$user_ip');";
$_SESSION['is_logged'] = true;
$_SESSION['Name'] = $guest;
}
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Session Start successfully\n";
mysql_close($conn);
My Idea is to get users IP and save it. If the user IP doesn`t exist in DataBase the Account will be created like "Guest1"... IPAdd "127.0.0.1";

You have 2 choices:
change the datatype of the IPAdd column from Unsigned Int to Varchar to save the ip in string format
convert the IP into long format before saving it by calling ip2long
As previously stated by another person, you should consider switching from mysql* to either mysqli or PDO_MySQL as the mysql* functions are deprecated.

You need to change the datatype of IPAdd, You can not save data like 127.0.0.1 or any IP address in integer field. You can save only positive or negative integer value without . in this field
change your datatype to varchar like this
ALTER TABLE `users` CHANGE `IPAdd` `IPAdd` VARCHAR( 20 ) NULL

change ipadd field to (int) and
use $_SERVER['SERVER_ADDR'] to get user system ip address..

Related

I want to implement something that doesn't allow the user to rate more than once

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.

adding counter to php page to count the unique visitors

I want to add a counter in my webpage which counts the number of visitors.
But my problem is that when i refresh my page ,counter increases by 1..i want that counter increases only when a new visitor with another ip reaches to my webpage.
here are my codes..
Sorry for my weak english
index.php
<?php
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$_SESSION['current_user'] = $ip;
if(isset($_SESSION['current_user']))
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
else
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
As database based solution is not preferred, You can try the following file based solution for counting unique visitor. You already have used counter.txt file in your code.
I tried to use the same file that you have used. In my case I am storing IP address in that file. I have used base64 encoding function just to hide the IP address. It is always good to keep that file in a safe place. If that file is lost then the unique visitor IPs will be lost. See the function below:
Function definition
function getUniqueVisitorCount($ip)
{
session_start();
if(!isset($_SESSION['current_user']))
{
$file = 'counter.txt';
if(!$data = #file_get_contents($file))
{
file_put_contents($file, base64_encode($ip));
$_SESSION['visitor_count'] = 1;
}
else{
$decodedData = base64_decode($data);
$ipList = explode(';', $decodedData);
if(!in_array($ip, $ipList)){
array_push($ipList, $ip);
file_put_contents($file, base64_encode(implode(';', $ipList)));
}
$_SESSION['visitor_count'] = count($ipList);
}
$_SESSION['current_user'] = $ip;
}
}
Function call
$ip = '192.168.1.210'; // $_SERVER['REMOTE_ADDR'];
getUniqueVisitorCount($ip);
echo 'Unique visitor count: ' . $_SESSION['visitor_count'];
Output
Unique visitor count: 2
Change:
if(isset($_SESSION['current_user']))
to:
if($_SERVER['REMOTE_ADDR'] == $_SESSION['current_user'])
And, surely you dont need to get $count from a file, and then write the same value back to the file...? If the $_SERVER['REMOTE_ADDR'] matches the SESSION['current_user'] then do nothing..
try to store the user IP in database and check for unique user,
<?php
session_start();
if (!$_SESSION['status']) {
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("ip_log", $connection);
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `database`.`table` (IP) VALUES ('$ip')");
mysql_close($connection);
$_SESSION['status'] = true;
}
?>
Best And Easy Code
Try to store the user IP in database and check for unique user
$`servername` = "";
$username = "";
$password = "";
$`dbname` = "";
$`conn` = new `mysqli`($`servername`, $username, $password, $`dbname`);
if ($`conn`->connect_error) {
die("Connection failed: " . $`conn`->connect_error);
}
$address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$name = `gethostname`();
$re = "select * from visitor where name='$name'";
$call = `mysqli_fetch_array`($re);
$as = `mysqli_num_rows`($call);
if($as == 0){
$`sql` = "UPDATE visitor SET visits = visits+1 WHERE name = '$name'";
}else{
$`sql` = "INSERT INTO visitor(visits,name,address) VALUE(1,'$name','$address')";
}
$`conn`->query($`sql`);
$`sql` = "SELECT visits FROM visitor WHERE id = 1";
$result = $`conn`->query($`sql`);
if ($result->`num_rows` > 0) {
while($row = $result->fetch_assoc()) {
$visits = $row["visits"];
}
} else {
$visits = "";
//echo $visits;
}
`$conn`->close();

I want to get each visitor count those who are visiting my website and want to display in index page

I want to get each visitor count those who are visiting my website and store to database.correct me.
I have used:
$client = $_SERVER['HTTP_CLIENT_IP'];
$remote = $_SERVER['REMOTE_ADDR'];
I don't understand which one i have to use. beacuse i have hosted in server . I have checked both.
echo $client; //no output
echo $remote; //163.53.204.24
This gives you the user's IP:
$_SERVER['REMOTE_ADDR'];
Table
create table visitors (
id int not null auto_increment,
ip varchar(32) not null,
visits int not null default 0,
primary key(id)
)engine=innodb;
Code
$visitor = $_SERVER['REMOTE_ADDR'];
$db = mysql_connect('','','');
$query =
mysql_query('select * from visitors where ip = \''.$visitor.'\';');
if (mysql_num_rows($query) == 0) {
mysql_query('insert into visitors (ip) values (\''.$visitor.'\');');
} else {
$row = mysql_fetch_array($query)
$id = $row[0]['id'];
$visits = $row[0]['visits'];
++$visits;
mysql_query('update visitors set visits = ' . $visits . ' where id = ' . $id);
}
mysql_close($db);
I haven't tested this, but, it should be pretty close.

Efficiently Banning IPs Using php and mysql?

CREATE TABLE `banned_ip` (
`id` INT( 25 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`ip` VARCHAR( 25 ) NOT NULL ,
`reason` TEXT NOT NULL )
Config.php
<?php
// config
$config['host'] = "localhost"; // host name of your mysql server
$config['user'] = "username"; // your mysql username
$config['pass'] = "password"; // your mysql password
$config['db'] = "database"; // the database your table is in.
// the # sign is an error supressor, meaning we can use our own error messages, this connects and selects db
#mysql_connect("$config[host]","$config[user]","$config[pass]")
or die("There was an error connecting to the database, MySql said:<br />".mysql_error()."");
#mysql_select_db("$config[db]")
or die("There was an error connecting to the database, MySql said:<br />".mysql_error()."");
?>
Ban.php
<?php
include("connect.php");
$ip = $_SERVER['REMOTE_ADDR'];
$find_ip = mysql_query("SELECT * FROM banned_ip WHERE ip='$ip'");
$ban = mysql_fetch_array($find_ip);
if($ip == $ban['ip']){
die("You are banned from this site!");
else {
echo "Your Were not Banned";
$sql = "INSERT INTO user(ip) VALUES('$ip')";
}
?>
What I am doing is check my database for a ip , if it is banned or not. IF not banned, Showing him message "Your Were not Banned" and banning him.
Storing his ip in database. And then if he comes again on site, is will be show "You are banned from this site!"
By this i am giving each ip only one time access to my content. Is this script efficeint enough? This script is not working for me. It is not banning my ip , instead it keeps showing me my content.
You are working with different tables obviously. You do a select query for banned_ip, to check if the IP is banned. But if he is not banned, you try to insert into the user table. This way you do note down all banned IPs, but you don't select them.
Also, when you query the database, it's bad behaviour to do SELECT *. Select only the values you need (in this case it doesn't even matter what, since you check if he finds an row for the ip).
There's never a 100% sure way to prevent non-logged-in users from accessing content. If you ban an IP, you might ban several persons at once (like schools). Using cookies (and also Sessions) is not efficient enough, since the cookie can be deleted.
<?php
include("connect.php");
$ip = $_SERVER['REMOTE_ADDR'];
$find_ip = mysql_query("SELECT ip FROM banned_ip WHERE ip='$ip'");
$ban = mysql_fetch_array($find_ip);
if($ip == $ban['ip']){
die("You are banned from this site!");
else {
echo "Your Were not Banned";
$sql = "INSERT INTO banned_ip (ip) VALUES('$ip')";
}
?>
<?php> include "connect_to_mysql.php";
$proxy_headers = array(
'HTTP_VIA',
'HTTP_X_FORWARDED_FOR',
'HTTP_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED',
'HTTP_CLIENT_IP',
'HTTP_FORWARDED_FOR_IP',
'VIA',
'X_FORWARDED_FOR',
'FORWARDED_FOR',
'X_FORWARDED',
'FORWARDED',
'CLIENT_IP',
'FORWARDED_FOR_IP',
'HTTP_PROXY_CONNECTION'
);
foreach($proxy_headers as $x){
if (isset($_SERVER[$x])) die("You are using a proxy!");
}
$counter = 1873;
$MM_redirectLoginFailed = "sorry_search.php";
$MM_redirecttoReferrer = false;
$dynamicList="";
$dynamicListaa="";
$sql = mysql_query("SELECT * FROM ip WHERE ip LIKE '%54.36.%'");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$product_name = $row["ip"];
$counter++;
$sql2 = mysql_query("INSERT INTO bannedIp (bannedip_id, bannedip) VALUES ('".$counter."', '".$product_name."')") or die(mysql_error());
echo $sql2;
print($product_name);
}
} else {
header("Location: ". $MM_redirectLoginFailed );
}
$ip = $_SERVER['REMOTE_ADDR'];
$find_ip = mysql_query("SELECT * FROM bannedIp WHERE bannedip='$ip'");
$ban = mysql_fetch_array($find_ip);
if($ip == $ban['bannedip']){
die("You are banned from this site2!");
}
$ip_parts = explode (".", $_SERVER['REMOTE_ADDR']);
$parts = $ip_parts[0] . $ip_parts[1];
if($parts == 5436)
{
die("You are banned from this site1!");
}
<?>

getting error in my php query

I am getting an error message in my php query.
Error being displayed:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1294251744','127.0.0.1','/register')' at line 2
my code:
<?php
require_once("includes/database.php");
//Set timeout to 5 minutes
$timeoutseconds = 300 ;
//get the time
$timestamp = time();
//Delete all users that are no online after the time out allowed
$timeout = $timestamp - $timeoutseconds ;
// stores users IP addresss
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/');
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
$result = mysql_query($sql, $conndb) or die(mysql_error());
//delete values when they leave
mysql_query("DELETE FROM totalonline WHERE timestamp < $timeout");
//grab the results
$sql = "SELECT DISTINCT ip FROM totalonline WHERE file='$path' ";
$result = mysql_query($sql, $conndb) or die(mysql_error());
//number of rows = the number of people online
$user = mysql_num_rows($result);
//spit out the results
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User online";
}
?>
Change this:
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
to this:
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES ('$timestamp','$user_ip','$path')";
You had two single quotes instead of one.
Also, near the end, you probably want to change this:
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User online";
}
to this:
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User offline";
}
You have double ' in the values field;)
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
Right before $timestamp.
It's better to do
//insert the values
$sql = 'INSERT INTO totalonline(timestamp, ip, file)
VALUES ('.$timestamp.',"'.$user_ip."',"'.$path.'")';
because that way you make sure the db understands ip and path are strings.

Categories