Hence my question, can this be exploited; or can only database inputs be exploited? (Just trying to be extra-cautious!)
If you are following the convention that no input should be trusted, then you should definitely validate the IP and as stated above, reject the submission if it is not a valid IP. Otherwise, if you store the IP it is the real IP, unless of course as pointed out above, they are using a proxy, in which case you won't see the user's real IP.
So to check for malicious behavior, the real issue is what you want to allow and when you are checking.
If you are checking the IP on every page and logging them out, as some super secure sites do, if their IP changes; then you will need to decide when to kick them. My host provider for example will only log you out if the IP has changed "significantly". I suppose this could mean the top 3 blocks of the IP.
On the other hand if you just want to store their IP then with what you have above, what you are storing is going to be the IP used to access the referrer page to that php script.
If you want to know if something strange is going on, you could store a session variable and store the IP when the session is created, then compare the initial IP with the referrer page IP that you are about to write to the DB. If they are different then MAYBE something is up. But it is not necessarily malicious behavior
If the visitor is on a dial up connection, and they lost the connection, then when they return they will most likely have a different IP, but it should not be "signficantly" different. To help prevent a false positive in this situation you could check the first 3 blocks of the IP and if they are the same you might say, OK he's logging in from the same ISP.
If they are on aol, the IP can change, but probably not "significantly". In any event if you are looking at X-Forwarded-For this is a non-issue, because you will not see the AOL proxy, you will see the real user IP.
That .htaccess code will be a lot slower than a php script that does the same checks. In any event those checks won't detect any serious proxy user who is using a so-called elite proxy or a botnet.
If they are using an anonymous proxy that changes their IP every x seconds, then you will quite possibly see two different IPs with this situation and they would most likely be significantly different IPs.
If they are a sophisticated hacker using a botnet, then their IP could be static for the whole session, but next time they come back they could quite likely have a completely different IP.
[edited by: sundaridevi at 1:46 pm (utc) on Mar 7, 2011]