About Webdrips

Webdrips is a Web Development and Digital Consulting Agency specializing in the design and development of websites using Drupal and Wordpress technology. Our focus is to support the Open Source community and businesses community with helpful contributions in business and technology.

Let's Work Together

[email protected] 

Drupal 7: Determine if a Path was Viewed by a User in a Given Timeframe

  • Dan Harris

Below is a method to determine if a user has visited a page on your site within the last four weeks at login, and if not, remind them what a wonderful page it is.

Code for determining if a Drupal page was visited image

You can accomplish exactly that by calling the following function from hook_login():

/**
* Check if a site url has been visited in a specified interval.
*
* @param $uid The user ID of the user to check.
*   Example: 200 
*
* @param $path The internal Drupal path.
*   Example: 'node/1' or 'mypage'
*
* @param $interval An interval MySQL understands
*   Example: '5 DAY' or '5 WEEK' (note value is not plural)
*/
function check_page_visited_in_time_interval ($uid, $path, $interval) {
 if (module_exists('statistics')) {
   // Original SQL
   $sql = 'SELECT timestamp FROM `accesslog` 
           WHERE uid = $uid 
           AND path = $path 
           AND `timestamp` > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL $interval));';        

   $date = date_create();
   date_modify($date, '-'.$interval);
   $interval =  $date->format('U');

   $result = db_query("
   SELECT timestamp 
   FROM accesslog
   WHERE uid = :uid 
   AND path = :path
   AND timestamp > :interval",
   array(':uid'=>$uid,
         ':path'=>$path,
         ':interval'=>$interval))->fetchAll();
             
   foreach($result as $r) {
     $time[$r->timestamp] = $r->timestamp;
   }
   $rowcount = count($time);
   if ($rowcount > 0) {
     return TRUE;
   }
 }
 return FALSE;
}
?>

TAGS : Code Example