Mark
Mark

Reputation:

PHP Unique IP content

Is it possible to show a visitor on my website a piece of text every 24 hours depending on their IP address, for example if the user visits my website a piece of text will be shown, however if the user visits the website again within 24hours the piece of text will be hidden until 24hours have passed?

Upvotes: 0

Views: 311

Answers (2)

maraspin
maraspin

Reputation: 2393

Your safest bet, if you have authentication in place is to use it, and store something associated to authenticated user (IE an attribute/field on db), expiring afer 24 hours.

Problem with cookies is that they'll only work if access happens from same host. If a user visits you from home, and then office, she might get the message twice. IP based checks can also work for you, but they can also be fooled by things such as proxies and natting.

In that case what you'd have to do is making a query on a 2 field (IP, last_time_displayed_message) table and show the message only if now - such_time is greater than 24 hours.

You could also try to get remote IP using something like what follows (attempt to check behind proxies) trying to prevent IP detection to be fooled:

function getIp() {
    $as_sources = array('HTTP_CLIENT_IP',
       'HTTP_X_FORWARDED_FOR',
       'HTTP_X_FORWARDED',
       'HTTP_X_CLUSTER_CLIENT_IP',
       'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED',
       'REMOTE_ADDR'
    );

    foreach ($as_sources as $s_key) {
        if (array_key_exists($s_key, $_SERVER)) {
             $s_regexp = "([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})";
             $s_ip = $_SERVER[$s_key];
             $b_validate = preg_match($s_regexp, $s_ip); 
             if ($b_validate !== false) {
                    return $s_ip;
             }
        }
    }

 // THROW AN EXCEPTION

}

Upvotes: 0

phihag
phihag

Reputation: 287835

Simply set a cookie with timeout:

if (!isset($_COOKIES['showFortune'])) {
  setcookie('showFortune', time(), time() + 24 * 60 * 60);
  $ip = $_SERVER['REMOTE_ADDR'];

  // Insert your IP-specific content here
  echo 'Hello ' . $ip . '!';
}

You can also identify the user by IP, but that fails in the presence of NAT and dynamic addresses, and requires a database.

Upvotes: 4

Related Questions