Advertisement
mkv

tracking hit counter

mkv
Jan 23rd, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.50 KB | None | 0 0
  1. <?php
  2.  
  3. // Create a connection to the database
  4. $database = new mysqli('localhost', 'username', 'password', 'databasename') or die('Could not connect to database');
  5.  
  6. // Ensure that the user input is available and safe
  7. if (!isset($_REQUEST['file'])) die('no file id provided');
  8.  
  9. $file = $_REQUEST['file'];
  10. if (preg_match("/[^0-9]/", $file))        die('bad file');
  11.  
  12. $ip = $_SERVER['REMOTE_ADDR'];
  13. if (preg_match("/[^a-fA-F0-9\.:]/", $ip)) die('bad ip');
  14.  
  15. // Add this visitor to the list
  16. $database->query("insert into ipcounter values(0, '$file', '$ip', now())") or init();
  17.  
  18. // Do a mysql "search" to get the hitcounter
  19. $result = $database->query("select count(distinct ip) hits from ipcounter where file = '$file'") or die('error selecting hit count');
  20.  
  21. // Read the result
  22. if ($result = $result->fetch_assoc())
  23. {
  24.     // Show the hitcount
  25.     echo $result['hits'];
  26. }
  27. else init();
  28.  
  29.  
  30.  
  31. // This will create the required table if something goes fuck
  32. function init()
  33. {
  34.     global $database;
  35.  
  36.     echo 'Re-initializing database due to error: ' . $database->error;
  37.  
  38.     $database->query('drop table if exists ipcounter') or die('could not delete table: ' . $database->error);
  39.     $q = <<<Q
  40. create table if not exists ipcounter (
  41.     id int(11) not null auto_increment,
  42.     file int(11) not null,
  43.     ip varchar(45) not null,
  44.     time timestamp not null default current_timestamp,
  45.     primary key (id),
  46.     key (ip))
  47. Q;
  48.     $database->query($q) or die('could not create table: ' . $database->error);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement