Hello folks, What I want is to show certain content (image) only once for each visitors of my website based on their IP address (or anything). Is there a way to do this? Thanks.
Edit. My bad, I thought this was the PHP forum! Sorry I'd probably use a cookie. if(isset($_COOKIE['one_view'])) { //Already seen content } else { setcookie('one_view', true); //Content } PHP:
Hi D3Tek, I will add the above code in .js file then add the following code on the site where I want it to show? <script type="text/javascript" src="code.js"></script> PHP: Is this how it works? Or is it PHP?
In JS, you can just use cookies and/or HTML5 local storage. Note that obviously because you are relying on cookies, as well as client Javascript code, you cannot strictly enforce the rule you want as people could block javascript on the page, clear their cookies, and so on.
I would not use Cookies, if cookies are blocked or cleaned they can return. Here is what you need to do , create a table called in MySQL IP_used . ( If you dont know how create a mysql table go search in youtube you will get it is very easy ) Suppose this table have two fields id and ip_address here is the code you need $link = mysql_connect("Localhost",user,pass) or die("Could not connect"); mysql_select_db($databasename,$link) or die("Could not select database"); $data = mysql_query("select * from IP_used where ip_address='".$_SERVER['REMOTE_ADDR']."'"); if(mysql_num_rows($data)>0){ // this ip address have seen the content once }else{ // this ip address is a new one // show him what you want to show // after showing his address you can add his IP address to the table too $ins = mysql_query("insert into IP_used('ip_address') values('".$_SERVER['REMOTE_ADDR']."') "); } PHP: I didn't run the code , check if you have any issues let me know
There is certainly one issue, the mysql query is not sanitized. While $_SERVER['REMOTE_ADDR'] is generally secure as far as I am aware you should always sanitize any variables in your queries. This ensures maximum security and the additional effort required to write a prepared statement is very small.
Thanks for Pointing that out @MakZF Just you let you know sanitize is for the protection from SQL injection and only required for $_POST, $_GET , not $_SERVER variables. Their is no harm in adding mysql_real_escape_string... but I dont see any use as well
Thanks Manish, but how I can insert this on my website footer? it is a Mybb forum. Also is there a way to do this with Javascript? Appreciate your help.
There's nothing wrong with using a cookie. You could use cookies/sessions and have the same success rate as your MySQL script. You haven't accounted for people with dynamic IP's, so my method may only fail when someone isn't using cookie's or is smart enough to clear their browser data, but your script would allow me to view the content all of the time because my IP changes. Not forgetting that also, MySQL is out-dated and no longer supported. You should use PDO or MySQLi. EDIT: As for doing it in JS, you could try: <script type="text/javascript"> function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } </script> </head> <body> <script type="text/javascript"> if(!readCookie('view_once')){ document.write('Test, Test, Test'); createCookie('view_once', 'view_once', 6 * 3000); } </script> HTML:
... and part of why we've been told for EIGHT BLASTED YEARS to stop using mysql_ functions and use mysqli or PDO instead... on top of things like prepared queries being native, reusable, reusable data sets, and no longer having the connection global in scope (which was ALWAYS serious herpafreakingderp territory) -- hence those nice big red warning boxes they added a year and a half ago now saying "FOR **** SAKE STOP USING THIS ALREADY!?!" Which is why that code should look something more like this: <?php $db = new PDO( 'mysql:host=localhost;dbname=iptracking', 'username', 'password' ); $ipData = [ ':ip' => $_SERVER['REMOTE_ADDR'] ]; $statement = $db->prepare(' SELECT count(*) FROM ip_used WHERE ip_address = :ip '); $statement->execute($ipData); if ($statement->fetchColumn() == 0 ) { // add to list $statement = $db->prepare(' INSERT INTO ip_used ( ip_address ) VALUES ( :ip ) '); $statement->execute($ipData); // do whatever it is you are doing for first-visit } else { // subsequent visit content here } ?> Code (markup): It's also usually faster to return a count than the actual stored data.... Just saying... ... and YES, you should sanitize $_SERVER vars, it is entirely possible to spoof the IP address on a request -- it just means it will fail to return properly on handshaking... though IP is harder to spoof than say... HTTP_REFERRER or HTTP_USER_AGENT, which are WAY too easy to screw with WITHOUT having any sort of real impact on the handshake or data return.
Apart from the increased overhead on the handshake -- though that really comes down to how many cookies you set, how many files per page there are coming from the same host, and how well you're controlling when and what they are sent with. (static separate domains and turning off unneeded requests via filtering for example could help). Personally, I'm just not wild about using client side code for something like this... it's just more script-tard bull at that point. THOUGH - I'd use cookies server side for this; no need to get client-side involved. Check the cookie, not set show image and set cookie. People unsetting cookies is far less of a problem than how using a database effectively blacklists IP addys -- so dynamic IP's or people sharing IP's could end up pretty much never seeing that 'first visit' image when they really should. <?php // do this FIRST before any code is output!!! if ($notVisited = !isset($_COOKIE['hasVisited'])) { setcookie('hasVisited','1', 34158204720); // 6th June 3052, long joke } /* do all your normal code here, when you get to where you want your image: */ if ($notVisited) { /* output your image or whatever */ } ?> Code (markup): Which is about as simple as you can get... and wouldn't waste time sending code client-side that doesn't need to be sent.
Which is pretty much exactly what I was getting at. The method I suggested is way less resource intensive and there is absolutely no need for using the database.And the comments about he "overhead" are void because there isn't any. I'd understand if I'd set 1,000 cookies and 200 if statements.
There will never be a 100% sure way to do this, and if you want to be absolutely sure that the user only sees an image once, you'll have to do it after a login or something similar. Cookies: what if I use a different browser the second time around? IPs: what if (which most do) my ISP assigns IPs dynamically? Both cookies and IPs: see above. Cookies, IP and user-agent: pretty much the same problems. Different browser, different computer, different OS etc. The easiest way would be to just use a cookie, really - simply because the rest only adds to the complexity, and doesn't really give any reward. Doing this in javascript doesn't make much sense either, as you can do it in a few lines server-side. As for the handshake-argument, it doesn't matter much when you have a few users. If your site serves a million users at the same time, those extra bytes becomes quite a few...
I agree, I did not account the IP address being dynamic... I guess both ideas have it advantages and disadvantages. Specially he is after Javascript and added to OS Mybb. Regarding the MYSQL is not supported and must use Mysqli, the sites that are massive and have been working since 2002, with millions of lines of code. Changing a DB cannot happen Over night.. thanks for the suggestion...
It also shouldn't take eight years, and most likely not even get started on ACTUALLY being done until after it's removed from PHP entirely -- which at this point seems to be what they're going to have to do in terms of forcing people to pull their craniums out of the 1990's rectum. (same goes for HTML, which is why the W3C just kind of gave up and with HTML 5 says "go ahead and sleaze things out any old way" - REALLY hope PHP doesn't end up following in their footsteps.)