Log in

View Full Version : Resolved Will doing this function returns the ip address of user or the server ?



subins2000
12-25-2012, 06:06 AM
I am developing analytics site for my main site. I need to get the IP address of the user visiting. So I googled and i got a solution. But the solution is not working. The code is :-


function getUserIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
return $_SERVER['HTTP_CLIENT_IP'];
}else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
return $_SERVER['REMOTE_ADDR'];
}
}
mysql_query("INSERT INTO viewers (id,ip,p) VALUES('$uid','".getUserIpAddr()."','".$_POST['page']."')");


This works fine in localhost server, but it isn't working on Internet Server. Can someone please help me.
I think the problem is with empty function.

traq
12-25-2012, 06:31 AM
...the solution is not working.
"not working" is useless information. Of course it's "not working," after all, why would you be asking for help if it was working?

Instead, tell us:

1. What did you expect to happen?
2. What actually happened?
3. What have you done to try and figure out why (or even, what's your guess at what went wrong)?


This works fine in localhost server, but it isn't working on Internet Server. Can someone please help me.
That might indicate some difference in configuration between the servers - in their error handling, or in how they set their environment vars ($_SERVER, etc.). Did you get any error messages? Did you use the same browser to test in both cases?

On a related note, if you haven't already, I'd highly recommend checking with your web host before implementing any analytics code.
Many hosts:
-- prohibit data gathering for analytics, especially when using a database (because it's often expensive in processing terms)
-- have existing analytics tools, which are probably better than anything you might build yourself.



mysql_query("INSERT INTO viewers (id,ip,p) VALUES('$uid','".getUserIpAddr."','".$_POST['page']."')");
1. Do you have a defined constant named getUserIpAddr? Or are you actually trying to call your function (i.e., getUserIpAddr())?

2. You should never insert user-provided data (your POST var, in this case, but this also includes any SERVER vars that start with "HTTP_...") directly into the database.

Best Case, SQL errors and confusing script crashes.
Worst Case, SQL Injection Attacks.

You need to sanitize your data by using the appropriate escape functions (e.g., mysql_real_escape_string() - however, see #3 below.)

3. If at all possible, you should avoid using the mysql_* functions.

ext/mysql is severely outdated and scheduled for deprecation. It is no longer recommended for new projects, and existing code should be updated to avoid performance and security problems. Using ext/mysqli (http://php.net/mysqli) or the PDO class (http://php.net/pdo) is recommended. Read more about choosing an API (http://php.net/mysqlinfo.api.choosing) here.

subins2000
12-25-2012, 12:31 PM
"not working" is useless information. Of course it's "not working," after all, why would you be asking for help if it was working?

Instead, tell us:

1. What did you expect to happen?
2. What actually happened?
3. What have you done to try and figure out why (or even, what's your guess at what went wrong)?


That might indicate some difference in configuration between the servers - in their error handling, or in how they set their environment vars ($_SERVER, etc.). Did you get any error messages? Did you use the same browser to test in both cases?

On a related note, if you haven't already, I'd highly recommend checking with your web host before implementing any analytics code.
Many hosts:
-- prohibit data gathering for analytics, especially when using a database (because it's often expensive in processing terms)
-- have existing analytics tools, which are probably better than anything you might build yourself.


1. Do you have a defined constant named getUserIpAddr? Or are you actually trying to call your function (i.e., getUserIpAddr())?

2. You should never insert user-provided data (your POST var, in this case, but this also includes any SERVER vars that start with "HTTP_...") directly into the database.

Best Case, SQL errors and confusing script crashes.
Worst Case, SQL Injection Attacks.

You need to sanitize your data by using the appropriate escape functions (e.g., mysql_real_escape_string() - however, see #3 below.)

3. If at all possible, you should avoid using the mysql_* functions.

ext/mysql is severely outdated and scheduled for deprecation. It is no longer recommended for new projects, and existing code should be updated to avoid performance and security problems. Using ext/mysqli (http://php.net/mysqli) or the PDO class (http://php.net/pdo) is recommended. Read more about choosing an API (http://php.net/mysqlinfo.api.choosing) here.

Thank you for your information. I update the post. Please solve my problem.

traq
12-25-2012, 06:39 PM
Well, here's a basic -likely incomplete- example using mysqli (http://php.net/mysqli). To sanitize data for insertion, you might do something like:
<?php
// create a database connection using mysqli
$DB = new mysqli( 'databaseHost','username','password','databaseName' );

// sanitize the user-supplied data
$sanitized_POST_page = $DB->real_escape_string( $_POST['page'] );

/* get your other data */
$uid = "whatever, I don't know";
$uip = getUserIpAddr();

// query
$SQL = "INSERT INTO `viewers` (`id`,`ip`,`p`) VALUES( '$uid','$uip','$sanitized_POST_page' )";

// execute query
$DB->query( $SQL );

**********

You didn't answer if there were any error messages (and what they said)?
You also still haven't told us what is actually happening.

Is error reporting enabled on your host? Try adding this at the top of your scripts and see if it causes any error messages to be displayed:
<?php

error_reporting( -1 );
ini_set( 'display_errors','On' );

You might read the second half of this (http://www.dynamicdrive.com/forums/entry.php?269-Before-You-Start-the-basics-for-PHP-in-particular-and-for-programming-in-general) for more on basic troubleshooting.

**********

In order to do your troubleshooting, leave out the query for now. Just check the return value of the function.
function getUserIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
return $_SERVER['HTTP_CLIENT_IP'];
}else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
return $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
return $_SERVER['REMOTE_ADDR'];
}
}

print getUserIpAddr();

subins2000
12-26-2012, 06:19 AM
I created this function to get the IP address of client.


function getIP(){
$response=@file_get_contents('http://www.netip.de');
if (empty($response)){throw new InvalidArgumentException("Error contacting Geo-IP-Server");}
$patterns=array();
$patterns["IP"] = '#IP: (.*?)&nbsp;#i';
$patterns["country"] = '#Country: (.*?)&nbsp;#i';
$patterns["city"] = '#City: (.*?)<br#i';
foreach ($patterns as $key => $pattern){
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
return $ipInfo["IP"];
}

I have a doubt. If I run this code on my server. Will the script returns the IP address of client or the server ?

traq
12-26-2012, 09:09 PM
I have merged this new thread with your existing thread. Please don't start new threads on the same topic.

As I asked before, please format your code (use line breaks and indentation) to make it easier to read.

codethatisallononelineandhaslittleornowhitespaceisdifficulttoread,andpeoplewillbemorelikelytohelpyouiftheycanunderstandyourcode.

As to your question,

Will the script returns the IP address of client or the server ?

Have you tried it?


**********
While the site netip.de does include an IP address in its response, the response is not well-suited for use by PHP - it's a whole webpage, intended to be read by a person. Their aim is also to provide geographic/postal information (the IP address it includes is the one *you provide* when you request the page - which should probably answer your question about whose IP address it is).

Did you run into some problem with your original function? It was a better approach.

subins2000
12-27-2012, 04:01 AM
I have tried it and it returns the IP address of Server. When I'm using $_SERVER variable for finding IP address, it gave me an error. So I tried this new method. But I am getting the IP of Server.
Is there any other method than using $_SERVER variable to find IP address ?

traq
12-27-2012, 04:35 AM
When I'm using $_SERVER variable for finding IP address, it gave me an error.

What was the error? You need to provide this sort of information if you expect anyone to be able to help you.



Is there any other method than using $_SERVER variable to find IP address ?

Checking the value held in $_SERVER['REMOTE_ADDR'] is the most direct, reliable method (though it may point at a proxy (likely*)) or be spoofed or missing altogether (quite unlikely**)).

----------
* HTTP requests are rarely direct, and often pass through any number of proxies. Sometimes it "just happens" (e.g., when leaving your ISP's server), and sometimes it's deliberate (e.g., to protect a user's privacy).

** spoofing (falsifying) your IP address is entirely possible, and relatively simple. However, if a user doesn't provide a valid IP, the response will never find them - so doing so would be pointless, except in certain malicious attacks.

subins2000
12-28-2012, 03:21 PM
It worked when I used the error function you mentioned. I didn't know about this function. Thank you very much. You helped me a lot.

traq
12-28-2012, 09:15 PM
If your question has been answered, please mark your thread "resolved":
On your original post (post #1), click [edit], then click [go advanced]. In the "thread prefix" box, select "Resolved". Click [save changes].
If you have not already done so, you should also consider sharing the solution to your problem.
This may be beneficial to others who encounter similar issues.

subins2000
12-29-2012, 03:53 AM
I changed the code to this and it worked.

error_reporting( -1 );ini_set( 'display_errors','On' );
function getUserIpAddr(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
return $_SERVER['HTTP_CLIENT_IP'];
}else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ite=explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']); return str_replace(" ",'',$ite[0]);
}else{
return $_SERVER['REMOTE_ADDR'];
}
}
$ucip=getUserIpAddr();
$response=@file_get_contents('http://www.netip.de/search?query='.$ucip);if (empty($response)){throw new InvalidArgumentException("Error contacting Geo-IP-Server");}$patterns=array();$patterns["IP"] = '#IP: (.*?)&nbsp;#i';$patterns["country"] = '#Country: (.*?)&nbsp;#i';$patterns["city"] = '#City: (.*?)<br#i';foreach ($patterns as $key => $pattern){$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';}
$uip=$ipInfo["IP"];$uco=$ipInfo["country"];$uci=$ipInfo["city"];$ipInfo=explode('-',$ipInfo["country"]);$ucs=$ipInfo[0];
mysql_query("UPDATE stats SET week=week+1,views=views+1 WHERE id='$uid'");
mysql_query("UPDATE sites SET `$ucs`=`$ucs`+1");
mysql_query("INSERT INTO viewers (id,ip,p,city) VALUES('$uid','$ucip','".$_POST['page']."','$uci')");

I found out what the error was with the help of error_reporting( -1 );ini_set( 'display_errors','On' );. Thanks to traq (http://www.dynamicdrive.com/forums/member.php?29708-traq).