Jump to content

Grabbing Visitor's Ip


chibineku

Recommended Posts

I've been googling a lot, trying to find reliable ways of grabbing a user's IP address, and while I can find sites that are clearly grabbing mine, I can't seem to duplicate their efforts using the code provided. I don't know why. I figured that grabbing an IP address might be the easiest way to set session cookies without prompting the user for any information. I am trying to set the cookie in JavaScript, but I can switch to doing it in php if that's easier, though I'm aware that you can drop into php even mid-JS. Perhaps it's my application of the php IP grabbing code that is at fault. For example:

document.cookie="IP=<?php echo $_SERVER['REMOTE_ADDR'];  ?>"

I've tried also using @$REMOTE_ADDR.

Link to comment
Share on other sites

Session cookies? Why not use the $_SESSION array and related functions? Or do you mean something else? It is perhaps best not to use the word 'session' in a different context.Your echo $_SERVER['REMOTE_ADDR'] looks fine. When you View Source, does the correct value show up in the document? The cookie might not get set correctly, but you should still see the value in the source.Be aware that setting document.cookie with no expiration will cause the cookie to expire as soon as the browser leaves the page. So not too useful. Maybe that's the problem? You're looking for the cookie later and it's not there?Setting cookies directly from PHP is very easy. Just be aware that the cookie you set will not be available in the $_COOKIE array until the next time your script loads.

Link to comment
Share on other sites

Hiya. Thanks for the info. I never thought of checking the source for some reason. I've not got to sessions yet, and it was foolish to use that term. I just meant that it would be a useful way of tracking a user without having to ask for a piece of identifying information. My page to play with cookies only has a script that sets the cookie and a button that creates an alert with the cookie data, so the expiration isn't important in this case. I will keep trying, or just read up on php cookies (and sessions).Muchos gacias.

Link to comment
Share on other sites

Okay, so any ideas why the following doesn't work in FF, but it does in Safari, Opera, IE and Chrome?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Content-Type"content="text/html;charset=ISO-8859-1" /><title>Cookie Test</title><script type="text/javascript">var IP = "<?php echo $_SERVER['REMOTE_ADDR'];  ?>";var exp=new Date();var twoDays=exp.getTime()+(2*24*60*60*1000)exp.setTime(twoDays)document.cookie="IP="+IP+";expires="+exp.toGMTString()function checkCookie() {document.getElementById("cookie").innerHTML=document.cookie}</script></head><body onload="checkCookie()"><span id="cookie"></span></body></html>

Link to comment
Share on other sites

Works fine on my FF. Now, I didn't actually upload it to my server, so I swapped in some literal text for the php bit -- but the cookie is created (I see it in my preferences) and the cookie value prints out in the span.Clear your cache?

Link to comment
Share on other sites

I did...I cleared all private data. I'm not too fussed, obviously it's only there for me to play with the document.cookie object because it's new to me, and if it works on your FF, that's fine. Just in case it's the php part, could you please click here and see if it works?Arigato.

Link to comment
Share on other sites

I did...I cleared all private data. I'm not too fussed, obviously it's only there for me to play with the document.cookie object because it's new to me, and if it works on your FF, that's fine. Just in case it's the php part, could you please click here and see if it works?Arigato.
It's working properly in Firefox for me.
Link to comment
Share on other sites

It's working properly in Firefox for me.
That'll do for me. Thanks for checking.Now, the other matter is that this script only gets the IP address of the remote server, which isn't always the true client IP. Is there a way to verify that you're getting the IP of the visitor's terminal and not some mirror? It would be pretty rubbish, though probably pretty unlikely, if two or more people were routed through a server and ended up with the same IP address (plus it could constitute a security risk), or if you based some kind of content on someone's geographical location, only they aren't anywhere near there.
Link to comment
Share on other sites

Lots of corps and universities run all traffic through a proxy server. Websites only ever see the same IP address from the whole site, maybe thousands of computers. I think this practice may be losing some vogue, but I don't think there's much you can do about it. HTTP was never invented for everything we'd like it to do.I would do as little as possible with IP addresses. It's cute when I get a car ad from my area, but I wouldn't build serious security on the concept.EDIT. Bah, Scene 24. Twice in one day! I f@rt in your general direction!

Link to comment
Share on other sites

EDIT. Bah, Scene 24. Twice in one day! I f@rt in your general direction!
O.o say wha?Okay, that'll do for cookies - I need to trim down anyway...Bring on sessions.
Link to comment
Share on other sites

Resurrection:Will php and javascript read the same cookies, and if they both set one, will they be agglutinated like they would if they were all set by JS?I was thinking of having a php start session script at the top of a page:

<?phpif(isset($_SESSION['views']))$_SESSION['views']=$_SESSION['views']+1;else if($_COOKIE["views"])$_SESSION['views']=(echo $_COOKIE["views"]);else $_SESSION['views']=1?>

and then onunload, writing the value of $_SESSION['views'] to a cookie, but I can't find any event handlers in PHP (at least, not on the W3Schools tutorials - I do have a large book on php, so I will get around to checking for that later). So I wanted something like this to run on unload:

<script type="text/javascript">function leaveCookie() {var exp=new Date();var twoDays=exp.getTime()+(2*24*60*60*1000)exp.setTime(twoDays)document.cookie="views=<?php echo $_SERVER['views']; ?>; expires="+exp.toGMTString()}</script>

As issue is the way that php and JS read cookies. php lets you index it by name to return the value, but in JS you have to get a substring of the cookie, which is an issue if there were previous cookies set and you don't know where the name/value pair you want lies in the concatenated string. It's all too much for my noodle at 1:20am, so I will throw it to the experts.

Link to comment
Share on other sites

This new learning amazes me. Explain again how sheep's bladders can be employed to prevent earthquakes.
Do I detect a facetious note in your tone, sir? I'm not sure I follow, anyway. What is it that is so amazing/ludicrous?
Link to comment
Share on other sites

What? Scottish, but not a Monty Python fan? (The original levity came about because JSG and I posted essentially the same answer within 1-2 minutes of each other. It assumed the shape it did because JSG's current persona is taken from MP and the Holy Grail.)Anyway, as long as you don't do something strange with the path attribute, PHP and Javascript should have access to the same cookie. That is, the same name will retrieve the same data.You are correct that PHP simplifies the task of extracting cookies. The getCookie method described at the school is tolerable, or you could Google something that creates an array similar to $_COOKIE, or figure out how to make your own. Not very hard.

Link to comment
Share on other sites

So I wanted something like this to run on unload:
PHP doesn't have load and unload events, Javascript does. PHP runs before the page even loads. By the time the Javascript load event fires, PHP is already finished doing everything it needs to do. If you want PHP code to run when the user leaves the page, then you need to use a Javascript unload event to send an ajax request to run the PHP. I haven't found much use for running PHP on unload though.Also, with this line:$_SESSION['views']=(echo $_COOKIE["views"]);echo doesn't return anything, it just prints to the browser. If you run that line the value of $_SESSION['views'] will be null.
and then onunload, writing the value of $_SESSION['views'] to a cookie
Cookies are only sent to the browser when the page loads. Cookies are sent as HTTP headers, and the web server sends all headers before it sends the requested page. If you've sent any HTML output at all, the server has already sent all headers, including any cookies to set. If you try to set a cookie after that you're going to get an error.
which is an issue if there were previous cookies set and you don't know where the name/value pair you want lies in the concatenated string
You would just need to break up the string and loop through the pieces looking for the one you're after. For what it's worth though, I don't mix Javascript and PHP when dealing with cookies, I only use PHP. I haven't found a need to have Javascript modify one of the cookies I set with PHP. In fact, really the only thing I ever use cookies for is the "remember me" checkbox on a login form. For all other data I use sessions only.
Link to comment
Share on other sites

It's funny that Deirdre's Dad should say I'm not a Monty Python fan, given the bottom of my sig, but I am not fluent in it, so I didn't get the context. As far as British comedy goes, Monty Python has a place, but there's better: Fawlty Towers, Red Dwarf, Blackadder are all superior IMO. Back to coding: I will drop my silly ideas of combining php and JS. As I learn a little, I try to assimilate it into what I already know, with sometimes unusual and unusable results when there are already special ways of doing what I want lurking in the next chapter of my Bibles. I don't want to start yet another thread about books, but are there any that anyone would recommend for CSS? I know that I am a sap for buying books about this stuff when there is a plethora of information on the web and this here forum to get answers and help from, but I feel comforted knowing that I have a comprehensive compendium of information at my fingertips that feels real and solid.

Link to comment
Share on other sites

It's funny that Deirdre's Dad should say I'm not a Monty Python fan, given the bottom of my sig, but I am not fluent in it, so I didn't get the context. As far as British comedy goes, Monty Python has a place, but there's better: Fawlty Towers, Red Dwarf, Blackadder are all superior IMO.
Yes, how did I miss that? Red Dwarf rocks. Blackadder, too. I liked Reginald Perrin, but I haven't seen it in decades.I have O'Reilly's CSS Cookbook. It's in a "problem"-solution format, if you like that sort of thing. Not very friendly as a reference.
Link to comment
Share on other sites

Mastering Integrated HTML and CSS by Virginia DeBolt, published by SYBEX, ISBN 978-0-470-09754-0
But she has a woman's name, my Lord!Ahem.I feel more drawn to jlhaslip's suggestion, as I prefer a more textbooky book to the problem-solution kind - that's what you guys are for, after all ^.^ I was tempted to get the HTML, XHTML and CSS Bible, but it doesn't get good reviews on amazon and the chapter they let you look at, albeit the first one, is just too simple. I reckon many of its 600+ pages would be explanations designed to bring an 80yr old up to speed.D's D:I love when Americans have heard of British shows and enjoyed them - not to put too fine a point on it, but I once chatted with an American online who asked if Scotland was in Canada... Red Dwarf does rock. They made 3 new episodes this year, which I haven't actually seen, but it involves a visit to modern day Earth, including a stop by the set of Craig Charles' new place of work, The Rover's Return, from the soap opera Coronation Street. The mere thought makes me shudder. Have you seen Fawlty Towers? There are only 2 series of it, with a total of around 15 episodes, but every one is hysterical. Worth youtubing at worst, particularly The German's episode.
Link to comment
Share on other sites

I tried to like Fawlty Towers, but it didn't work for me. Not only am I looking forward to the new Red Dwarf stuff, but I am renting ALL the DVDs this summer so I can watch them in sequence with my daughter, who is just getting old enough (12) to like the things I like (e.g., the Beatles, who are also, I believe, not from Canada).Ever see the original Bedazzled, with Cook and Moore? I saw it on TV when I was a kid and laughed my arse off. And that skit they did, where Moore plays a 1-legged goalie? I still chuckle.(I know we're off topic, mods, but it is chibineku's thread after all.)

Link to comment
Share on other sites

That's OK, at least she doesn't have a man's name. Would you buy a book from Ms. Wayne DeBolt?
Hm...maybe you have a point.I've not seen the original Bedazzled, no. I have heard it's good. I think we may be divided when it comes to music, as the Beatles would definately form part of my "Really Literally In ###### Playlist". That said, I have diverse tastes, from Chris de Burgh (my dad used to play it a lot when I was a kid) to Tool, via Barenaked Ladies, Van Halen, Extreme, Pavarotti, Katy Perry, Marilyn Manson and many, many others. Speaking of mods, I forget they exist on this forum. The only other one I've been a part of, the mods were constantly stepping in as arguments and inappropriate posts were common. A question that is more on topic: if a session expires when you leave the website, how is website defined: I would guess it means if you leave the current domain, right?Off topic again: you didn't like Fawlty Towers? Hm. What will you tell your daughter when she asks what smeg means?Oh man, they bleeped the word...well, I can't say it, but it's just the short name for the underworld. Bah.
Link to comment
Share on other sites

A question that is more on topic: if a session expires when you leave the website, how is website defined: I would guess it means if you leave the current domain, right?
A session cookie is delivered as a temporary cookie. Different browsers may implement temporary cookies differently, but all of them will delete temporary cookies when you close the browser. If you navigate away from the domain I'm not sure if it will delete temporary cookies for the domain or not. In my experience most of them don't, they wait until you close the browser.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...