1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Show content only once per IP!

Discussion in 'JavaScript' started by microcon, Dec 2, 2013.

  1. #1
    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.
     
    microcon, Dec 2, 2013 IP
  2. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #2
    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:
     
    D3Tek, Dec 2, 2013 IP
  3. microcon

    microcon Well-Known Member

    Messages:
    216
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    120
    #3
    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?
     
    microcon, Dec 2, 2013 IP
  4. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #4
    No, no. My code is PHP - I thought the thread was in the PHP section. Sorry!
     
    D3Tek, Dec 2, 2013 IP
  5. microcon

    microcon Well-Known Member

    Messages:
    216
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    120
    #5
    Ok, how to do it with PHP?
     
    microcon, Dec 2, 2013 IP
  6. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #6
    Well, create a PHP page with your content on, and modify my code to work with that file
     
    D3Tek, Dec 2, 2013 IP
  7. MakZF

    MakZF Well-Known Member

    Messages:
    390
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    140
    #7
    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.
     
    MakZF, Dec 2, 2013 IP
  8. manish_khanna

    manish_khanna Member

    Messages:
    58
    Likes Received:
    6
    Best Answers:
    1
    Trophy Points:
    35
    #8
    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
     
    manish_khanna, Dec 2, 2013 IP
  9. MakZF

    MakZF Well-Known Member

    Messages:
    390
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    140
    #9
    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.
     
    MakZF, Dec 2, 2013 IP
  10. manish_khanna

    manish_khanna Member

    Messages:
    58
    Likes Received:
    6
    Best Answers:
    1
    Trophy Points:
    35
    #10
    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
     
    manish_khanna, Dec 2, 2013 IP
  11. microcon

    microcon Well-Known Member

    Messages:
    216
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    120
    #11
    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.
     
    microcon, Dec 3, 2013 IP
  12. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #12
    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:
     
    Last edited: Dec 3, 2013
    D3Tek, Dec 3, 2013 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    ... 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.
     
    deathshadow, Dec 3, 2013 IP
  14. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #14
    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.
     
    deathshadow, Dec 3, 2013 IP
  15. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #15
    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. ;)
     
    D3Tek, Dec 3, 2013 IP
  16. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #16
    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...
     
    PoPSiCLe, Dec 3, 2013 IP
    deathshadow likes this.
  17. microcon

    microcon Well-Known Member

    Messages:
    216
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    120
    #17
    Thank you guys for the support. :)
     
    microcon, Dec 3, 2013 IP
  18. microcon

    microcon Well-Known Member

    Messages:
    216
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    120
  19. manish_khanna

    manish_khanna Member

    Messages:
    58
    Likes Received:
    6
    Best Answers:
    1
    Trophy Points:
    35
    #19
    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...
     
    Last edited by a moderator: Dec 3, 2013
    manish_khanna, Dec 3, 2013 IP
  20. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #20
    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.)
     
    deathshadow, Dec 3, 2013 IP
    malky66 likes this.