PHP page view counter - php

I downloaded a php view counter and I set it the database but when it comes to show the hits I am getting error. The documentation says
USAGE:
In your script, use reqire_once() to import this script, then call the
functions like PHPCount::AddHit(...); See each function for help.
*
Here is my demo.php where I want to show the view. But it is throwing
Notice: Undefined variable: pageID in C:\xampp\htdocs\test\demo.php on line 4
1
<?php
include_once("hit.php");
echo //this is what I added.
PHPCount::AddHit($pageID);
?>
The below is hit.php and what I wanna know is how can I show the views on the above demo.php?
<?php
/*
* USAGE:
* In your script, use reqire_once() to import this script, then call the
* functions like PHPCount::AddHit(...); See each function for help.
*
* NOTE: You must set the database credentials in the InitDB method.
*/
class PHPCount
{
/*
* Defines how many seconds a hit should be rememberd for. This prevents the
* database from perpetually increasing in size. Thirty days (the default)
* works well. If someone visits a page and comes back in a month, it will be
* counted as another unique hit.
*/
const HIT_OLD_AFTER_SECONDS = 2592000; // default: 30 days.
// Don't count hits from search robots and crawlers.
const IGNORE_SEARCH_BOTS = true;
// Don't count the hit if the browser sends the DNT: 1 header.
const HONOR_DO_NOT_TRACK = false;
private static $IP_IGNORE_LIST = array(
'127.0.0.1',
);
private static $DB = false;
private static function InitDB()
{
if(self::$DB)
return;
try
{
// TODO: Set the database login credentials.
self::$DB = new PDO(
'mysql:host=localhost;dbname=test',
'root', // Username
'', // Password
array(PDO::ATTR_PERSISTENT => true)
);
}
catch(Exception $e)
{
die('Failed to connect to phpcount database');
}
}
/*
* Adds a hit to a page specified by a unique $pageID string.
*/
public static function AddHit($pageID)
{
if(self::IGNORE_SEARCH_BOTS && self::IsSearchBot())
return false;
if(in_array($_SERVER['REMOTE_ADDR'], self::$IP_IGNORE_LIST))
return false;
if(
self::HONOR_DO_NOT_TRACK &&
isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] == "1"
) {
return false;
}
self::InitDB();
self::Cleanup();
self::CreateCountsIfNotPresent($pageID);
if(self::UniqueHit($pageID))
{
self::CountHit($pageID, true);
self::LogHit($pageID);
}
self::CountHit($pageID, false);
return true;
}
/*
* Returns (int) the amount of hits a page has
* $pageID - the page identifier
* $unique - true if you want unique hit count
*/
public static function GetHits($pageID, $unique = false)
{
self::InitDB();
self::CreateCountsIfNotPresent($pageID);
$q = self::$DB->prepare(
'SELECT hitcount FROM hits
WHERE pageid = :pageid AND isunique = :isunique'
);
$q->bindParam(':pageid', $pageID);
$q->bindParam(':isunique', $unique);
$q->execute();
if(($res = $q->fetch()) !== FALSE)
{
return (int)$res['hitcount'];
}
else
{
die("Missing hit count from database!");
return false;
}
}
/*
* Returns the total amount of hits to the entire website
* When $unique is FALSE, it returns the sum of all non-unique hit counts
* for every page. When $unique is TRUE, it returns the sum of all unique
* hit counts for every page, so the value that's returned IS NOT the
* amount of site-wide unique hits, it is the sum of each page's unique
* hit count.
*/
public static function GetTotalHits($unique = false)
{
self::InitDB();
$q = self::$DB->prepare(
'SELECT hitcount FROM hits WHERE isunique = :isunique'
);
$q->bindParam(':isunique', $unique);
$q->execute();
$rows = $q->fetchAll();
$total = 0;
foreach($rows as $row)
{
$total += (int)$row['hitcount'];
}
return $total;
}
/*====================== PRIVATE METHODS =============================*/
private static function IsSearchBot()
{
// Of course, this is not perfect, but it at least catches the major
// search engines that index most often.
$keywords = array(
'bot',
'spider',
'spyder',
'crawlwer',
'walker',
'search',
'yahoo',
'holmes',
'htdig',
'archive',
'tineye',
'yacy',
'yeti',
);
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
foreach($keywords as $keyword)
{
if(strpos($agent, $keyword) !== false)
return true;
}
return false;
}
private static function UniqueHit($pageID)
{
$ids_hash = self::IDHash($pageID);
$q = self::$DB->prepare(
'SELECT time FROM nodupes WHERE ids_hash = :ids_hash'
);
$q->bindParam(':ids_hash', $ids_hash);
$q->execute();
if(($res = $q->fetch()) !== false)
{
if($res['time'] > time() - self::HIT_OLD_AFTER_SECONDS)
return false;
else
return true;
}
else
{
return true;
}
}
private static function LogHit($pageID)
{
$ids_hash = self::IDHash($pageID);
$q = self::$DB->prepare(
'SELECT time FROM nodupes WHERE ids_hash = :ids_hash'
);
$q->bindParam(':ids_hash', $ids_hash);
$q->execute();
$curTime = time();
if(($res = $q->fetch()) !== false)
{
$s = self::$DB->prepare(
'UPDATE nodupes SET time = :time WHERE ids_hash = :ids_hash'
);
$s->bindParam(':time', $curTime);
$s->bindParam(':ids_hash', $ids_hash);
$s->execute();
}
else
{
$s = self::$DB->prepare(
'INSERT INTO nodupes (ids_hash, time)
VALUES( :ids_hash, :time )'
);
$s->bindParam(':time', $curTime);
$s->bindParam(':ids_hash', $ids_hash);
$s->execute();
}
}
private static function CountHit($pageID, $unique)
{
$q = self::$DB->prepare(
'UPDATE hits SET hitcount = hitcount + 1 ' .
'WHERE pageid = :pageid AND isunique = :isunique'
);
$q->bindParam(':pageid', $pageID);
$unique = $unique ? '1' : '0';
$q->bindParam(':isunique', $unique);
$q->execute();
}
private static function IDHash($pageID)
{
$visitorID = $_SERVER['REMOTE_ADDR'];
return hash("SHA256", $pageID . $visitorID);
}
private static function CreateCountsIfNotPresent($pageID)
{
// Non-unique
$q = self::$DB->prepare(
'SELECT pageid FROM hits WHERE pageid = :pageid AND isunique = 0'
);
$q->bindParam(':pageid', $pageID);
$q->execute();
if($q->fetch() === false)
{
$s = self::$DB->prepare(
'INSERT INTO hits (pageid, isunique, hitcount)
VALUES (:pageid, 0, 0)'
);
$s->bindParam(':pageid', $pageID);
$s->execute();
}
// Unique
$q = self::$DB->prepare(
'SELECT pageid FROM hits WHERE pageid = :pageid AND isunique = 1'
);
$q->bindParam(':pageid', $pageID);
$q->execute();
if($q->fetch() === false)
{
$s = self::$DB->prepare(
'INSERT INTO hits (pageid, isunique, hitcount)
VALUES (:pageid, 1, 0)'
);
$s->bindParam(':pageid', $pageID);
$s->execute();
}
}
private static function Cleanup()
{
$last_interval = time() - self::HIT_OLD_AFTER_SECONDS;
$q = self::$DB->prepare(
'DELETE FROM nodupes WHERE time < :time'
);
$q->bindParam(':time', $last_interval);
$q->execute();
}
}

You may need to specify the PageID
PHPCount::AddHit("index");

Related

Unable to get data from session after browser restart in php

Am using following lib to manage session, Am storing session values in database, everything works great i can get and set session values.
But after restart i can't get session values.
When i try to set session values i creates new row in database instead of updating.
LIB.php
<?php
/**
* #category Security
* #version 1.0
* #author First Last
* */
class mySessionHandler {
private $_db = NULL;
private $_table_name = 'sessions';
private $_cookie_name = 'session_cookie';
private $_seconds_till_expiration = 43200; // 2 hours
private $_renewal_time = 300; // 5 minutes
private $_expire_on_close = FALSE;
private $_ip_address = FALSE;
private $_user_agent = FALSE;
private $_secure_cookie = FALSE;
private $_session_id = FALSE;
private $_data = array();
public function __construct(array $config) {
$this->_setConfig($config);
if ($this->_read()) {
$this->_update();
} else {
$this->_create();
}
$this->_cleanExpired();
$this->_setCookie();
}
public function regenerateId() {
$old_session_id = $this->_session_id;
$this->_session_id = $this->_generateId();
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ?, session_id = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id, $old_session_id));
$this->_setCookie();
}
public function setData($key, $value) {
$this->_data[$key] = $value;
$this->_write();
}
public function unsetData($key) {
if (isset($this->_data[$key])) {
unset($this->_data[$key]);
}
}
function getData($key) {
return isset($this->_data[$key]) ? $this->_data[$key] : FALSE;
}
public function getAllData() {
return $this->_data;
}
public function destroy() {
if (isset($this->_session_id)) {
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
setcookie($this->_cookie_name, '', time() - 31500000, NULL, NULL, NULL, NULL);
}
private function _read() {
$session_id = filter_input(INPUT_COOKIE, $this->_cookie_name) ? filter_input(INPUT_COOKIE, $this->_cookie_name) : FALSE;
if (!$session_id) {
return FALSE;
}
$this->_session_id = $session_id;
$stmt = $this->_db->prepare("SELECT data, time_updated, user_agent, ip_address FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if (!$this->_expire_on_close && (($result['time_updated'] + $this->_seconds_till_expiration) < time())) {
$this->destroy();
return FALSE;
}
if ($this->_ip_address && ($result['ip_address'] != $this->_ip_address)) {
$this->_flagForUpdate();
return FALSE;
}
if ($this->_user_agent && ($result['user_agent'] != $this->_user_agent)) {
$this->_flagForUpdate();
return FALSE;
}
$this->_checkUpdateFlag();
$this->_checkIdRenewal();
$user_data = unserialize($result['data']);
if ($user_data) {
$this->_data = $user_data;
unset($user_data);
}return TRUE;
}return FALSE;
}
private function _create() {
$this->_session_id = $this->_generateId();
$stmt = $this->_db->prepare("INSERT INTO {$this->_table_name} (session_id, user_agent, ip_address, time_updated) VALUES (?, ?, ?, ?)");
$stmt->execute(array($this->_session_id, $this->_user_agent, $this->_ip_address, time()));
}
private function _update() {
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id));
}
private function _write() {
if (count($this->_data) == 0) {
$custom_data = '';
} else {
$custom_data = serialize($this->_data);
}
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET data = ?, time_updated = ? WHERE session_id = ?");
$stmt->execute(array($custom_data, time(), $this->_session_id));
}
private function _setCookie() {
setcookie(
$this->_cookie_name, $this->_session_id, ($this->_expire_on_close) ? 0 : time() + $this->_seconds_till_expiration, // Expiration timestamp
NULL, NULL, $this->_secure_cookie, // Will cookie be set without HTTPS?
TRUE // HttpOnly
);
}
private function _cleanExpired() {
if (mt_rand(1, 1000) == 1) {
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE (time_updated + {$this->_seconds_till_expiration}) < ?");
$stmt->execute(array(time()));
}
}
function _generateId() {
$salt = 'x7^!bo3p,.$$!$6[&Q.#,//#i"%[X';
$random_number = '9085723012206';
$random_txt = 'sanoj';
$ip_address_fragment = md5(substr(filter_input(INPUT_SERVER, 'REMOTE_ADDR'), 0, 5));
$hash_data = $random_number . $ip_address_fragment . $random_txt . $salt;
$hash = hash('sha256', $hash_data);
return $hash;
}
private function _checkIdRenewal() {
$stmt = $this->_db->prepare("SELECT time_updated FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if ((time() - $this->_renewal_time) > $result['time_updated']) {
$this->regenerateId();
}
}
}
private function _flagForUpdate() {
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '1' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
private function _checkUpdateFlag() {
$stmt = $this->_db->prepare("SELECT flagged_for_update FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if ($result['flagged_for_update']) {
$this->regenerateId();
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '0' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
}
}
private function _setConfig(array $config) {
if (isset($config['database'])) {
$this->_db = $config['database'];
} else {
throw new Exception('Database handle not set!');
}
if (isset($config['cookie_name'])) {
if (!ctype_alnum(str_replace(array('-', '_'), '', $config['cookie_name']))) {
throw new Exception('Invalid cookie name!');
} $this->_cookie_name = $config['cookie_name'];
}
if (isset($config['table_name'])) {
if (!ctype_alnum(str_replace(array('-', '_'), '', $config['table_name']))) {
throw new Exception('Invalid table name!');
} $this->_table_name = $config['table_name'];
}
if (isset($config['seconds_till_expiration'])) {
if (!is_int($config['seconds_till_expiration']) || !preg_match('#[0-9]#', $config['seconds_till_expiration'])) {
throw new Exception('Seconds till expiration must be a valid number.');
}
if ($config['seconds_till_expiration'] < 1) {
throw new Exception('Seconds till expiration can not be zero or less. Enable session expiration when the browser closes instead.');
}
$this->_seconds_till_expiration = (int) $config['seconds_till_expiration'];
}
if (isset($config['expire_on_close'])) {
if (!is_bool($config['expire_on_close'])) {
throw new Exception('Expire on close must be either TRUE or FALSE.');
}
$this->_expire_on_close = $config['expire_on_close'];
}
if (isset($config['renewal_time'])) {
if (!is_int($config['renewal_time']) || !preg_match('#[0-9]#', $config['renewal_time'])) {
throw new Exception('Session renewal time must be a valid number.');
}
if ($config['renewal_time'] < 1) {
throw new Exception('Session renewal time can not be zero or less.');
}
$this->_renewal_time = (int) $config['renewal_time'];
}
if (isset($config['check_ip_address'])) {
if (!is_string($config['check_ip_address'])) {
throw new Exception('The IP address must be a string similar to this: \'172.16.254.1\'.');
}
if (!preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $config['check_ip_address'])) {
throw new Exception('Invalid IP address.');
}
$this->_ip_address = $config['check_ip_address'];
}
if (isset($config['check_user_agent'])) {
$this->_user_agent = substr($config['check_user_agent'], 0, 999);
} if (isset($config['secure_cookie'])) {
if (!is_bool($config['secure_cookie'])) {
throw new Exception('The secure cookie option must be either TRUE or FALSE.');
}
$this->_secure_cookie = $config['secure_cookie'];
}
}
}
How do i get session values even after restarting browser,
GET.PHP
ob_start();
session_start();
include_once('index.php');
echo $session->getData('fname').'<br>';
echo $session->getData('password').'<br>';
echo $session->getData('email').'<br>';
SET.PHP
ob_start();
session_start();
include_once('index.php');
$session->setData('fname', 'first last');
$session->setData('password', '123456');
$session->setData('email', 'first#last.com');
$sesi = $session->_generateId();
echo $sesi;
$_SESSION['test'] = $sesi;
try replacing _setCookie() so that your cookie won't expire
private function _setCookie() {
setcookie($this->_cookie_name, $this->_session_id, ($this->_expire_on_close) ? 0 : time() + (10 * 365 * 24 * 60 * 60), //Expiration timestamp
NULL, NULL, $this->_secure_cookie, // Will cookie be set without HTTPS?
TRUE // HttpOnly
);
}

Throttling attempts not being recorded into database

Hi I am trying to create login throttling with object oriented php, I have successfully created it with structured code but I can not get it to work with object oriented so far heres the code:
public function find_failed_login($email = null) {
if(!empty($email)) {
$query = "SELECT * FROM {$this->table} WHERE email = '".$this->db->escape($email)."'";
return $this->db->query($query);
}
}
public function record_failed_login($email) {
$count = 1;
$time = time();
$failed_login = $this->find_failed_login($email);
if(!$failed_login) {
$query = "INSERT INTO {$this->table} (email, count, last_time) VALUES ('".$this->db->escape($email)."', {$count}, {$time})";
return $this->db->query($query);
} else {
$query = "UPDATE {$this->table} SET email = '{$email}', count = count + 1, last_time = {$time}";
return $this->db->query($query);
}
}
public function clear_failed_logins($email = null) {
if(!empty($email)) {
$failed_login = $this->find_failed_login($email);
if(isset($failed_login)) {
$query = "DELETE FROM {$this->table} WHERE email = '".$this->db->escape($email)."'";
return $this->db->query($query);
}
}
}
public function throttle_failed_logins($email = null) {
if(!empty($email)) {
$throttle_at = 3;
$delay_in_minutes = 1;
$delay = 60 * $delay_in_minutes;
$failed_login = $this->find_failed_login($email);
if(isset($failed_login)) {
while($failed = mysqli_fetch_assoc($failed_login)) {
if(isset($failed) && $failed['count'] >= $throttle_at) {
$remaining_delay = ($failed['last_time'] + $delay) - time();
$remaining_delay_in_minutes = ceil($remaining_delay / 60);
return $remaining_delay_in_minutes;
} else {
return 0;
}
}
}
}
}
and in the login page I am calling it like this:
$objLogin = new Login();
if($objForm->isPost('login_email')) {
$throttle_delay = $objLogin->throttle_failed_logins($objForm->getPost('login_email'));
if($throttle_delay > 0) {
$objValid->add2Errors('failed_logins');
}
when I try this I get no error or anything for that matter, its like it is dead code, would appreciate some professional help :)

Change Value of Static Property of a Class Using Setters and Getters

I want to extend this class (which I downloaded) to suit my own needs. When I run call this class I get an error complaining that there is an unexpected = in the constructor.
define("HIT_OLD_AFTER_SECONDS", 4 * 7 * 24 * 3600);
class PHPCount extends DatabaseObject {
protected static $table_name = "hits";
protected static $db_fields = array('pageid','isunique', 'hitcount','english_id');
public $pageid;
public $isunique;
public $hitcount;
public $english_id;
public static $article_id;
function __construct(){
return PHPCount::article_id = PHPCount::get_article_id();
}
public static function set_article_id($articleid){
PHPCount::article_id = $articleid;
}
public static function get_article_id(){
return PHPCount::article_id;
}
public static function AddHit($pageID, $visitorID){
HitTest::Cleanup();
self::CreateCountsIfNotPresent($pageID);
if(HitTest::UniqueHit($pageID, $visitorID)){
self::CountHit($pageID, true);
HitTest::LogHit($pageID, $visitorID);
}
self::CountHit($pageID, false);
}
/*
* Returns (int) the amount of hits a page has
* $pageID - the page identifier
* $unique - true if you want unique hit count
*/
public static function GetHits($pageID, $unique = false){
global $database;
self::CreateCountsIfNotPresent($pageID);
$pageID = $database->escape_value($pageID);
$unique = $unique ? '1' : '0';
$q = "SELECT hitcount FROM hits WHERE ";
$q .= get_article_id()=$pageID;
$q .=" AND isunique={$unique}";
$getHitCount = static::find_by_sql($q);
if(sizeof($getHitCount) >= 1){
foreach($getHitCount as $hit){
return (int)$hit->hitcount;
}
}else{
die("Fatal: Missing hit count from database!");
}
}
/*
* Returns the total amount of hits to the entire website
* When $unique is FALSE, it returns the sum of all non-unique hit counts
* for every page. When $unique is TRUE, it returns the sum of all unique
* hit counts for every page, so the value that's returned IS NOT the
* amount of site-wide unique hits, it is the sum of each page's unique
* hit count.
*/
public static function GetTotalHits($unique = false){
//global $phpcount_con;
$total = 0;
$unique = $unique ? '1' : '0';
$q = "SELECT hitcount FROM hits WHERE isunique={$unique}";
$count = static::find_by_sql($q);
foreach($count as $hit){
$total += (int)$hit->hitcount;
}
return $total;
}
private static function CountHit($pageID, $unique){
global $database;
$unique = $unique ? '1' : '0';
$safeID = $database->escape_value($pageID);
$q ="UPDATE hits SET hitcount = hitcount + 1 WHERE ";
$q .=get_article_id()=$safeID;
$q .=" AND isunique={$unique}";
mysqli_query($database->connection,$q);
}
private static function CreateCountsIfNotPresent($pageID){
global $database;
$pageID = $database->escape_value($pageID);
$q = "SELECT pageid FROM hits WHERE ";
$q .=get_article_id()=$pageID;
$q .=" AND isunique='0'";
$createCount = static::find_by_sql($q);
if($q === false || sizeof($createCount) < 1){
$sql ="INSERT INTO hits(";
$sql .=get_article_id();
$sql .=", isunique, hitcount) VALUES(";
$sql .=$pageID;
$sql .=", '0', '0')";
mysqli_query($database->connection,$sql);
}
//check unique row
$q ="SELECT "get_article_id();
$q .=" FROM hits WHERE ";
$q .=get_article_id()=$pageID;
$q .=" AND isunique='1'";
$createCount = static::find_by_sql($q);
if($q === false || sizeof($createCount) < 1){
$sql ="INSERT INTO hits (";
$sql .=get_article_id();
$sql .=", isunique, hitcount) VALUES('$pageID', '1', '0')"
mysqli_query($database->connection,$sql);
echo mysqli_error($database->connection);
}
}
}
Access to static class variables require a $-sign like here:
PHPCount::$article_id
Thus, at least these methods need to be changed.
// I'd propose to pass the article ID as a parameter here
function __construct( $theArticleID ){
PHPCount::$article_id = $theArticleID;
}
public static function set_article_id($articleid){
PHPCount::$article_id = $articleid;
}
public static function get_article_id(){
return PHPCount::$article_id;
}

Login using database sessions?

I have been trying to get my login script to work with database managed sessions.
This is my database session class:
class SessionManager {
var $life_time;
function SessionManager() {
// Read the maxlifetime setting from PHP
$this->life_time = 600; //10 minutes
// Register this object as the session handler
session_set_save_handler(array( &$this, "open" ),
array( &$this, "close" ),
array( &$this, "read" ),
array( &$this, "write"),
array( &$this, "destroy"),
array( &$this, "gc" )
);
}
function open( $save_path, $session_name ) {
global $sess_save_path;
$sess_save_path = $save_path;
// Don't need to do anything. Just return TRUE.
return true;
}
function close() {
return true;
}
function read( $id ) {
// Set empty result
$data = '';
// Fetch session data from the selected database
$time = time();
$newid = mysql_real_escape_string($id);
$sql = "SELECT
`session_data`
FROM
`sessions`
WHERE
`session_id` = '$newid'
AND
`session_expire` > $time";
$rs = mysql_query($sql);
$a = mysql_num_rows($rs);
if($a > 0) {
$row = mysql_fetch_assoc($rs);
$data = $row['session_data'];
}
return $data;
}
function write($id, $data) {
// Build query
$time = time() + $this->life_time;
$newid = mysql_real_escape_string($id);
$newdata = mysql_real_escape_string($data);
$sql = "INSERT INTO `sessions` (`session_id`, `session_data`,
`session_expire`, `session_agent`,
`session_ip`)
VALUES
(\"".$id."\", \"".$data."\",
\"".time()."\",\"".$_SERVER['HTTP_USER_AGENT']."\",
\"".$_SERVER['REMOTE_ADDR']."\")
ON DUPLICATE KEY UPDATE
`session_id` = \"".$id."\",
`session_data` = \"".$data."\",
`session_expire` = \"".time()."\"";
$rs = mysql_query($sql) or die(mysql_error());
return true;
}
function destroy($id) {
// Build query
$id = mysql_real_escape_string($id);
$sql = "DELETE FROM `sessions` WHERE `session_id`='$id'";
mysql_query($sql);
return true;
}
function gc(){
// Garbage Collection
// Build DELETE query. Delete all records who have passed the expiration time
$sql = 'DELETE FROM `sessions` WHERE `session_expire` < UNIX_TIMESTAMP();';
mysql_query($sql);
// Always return TRUE
return true;
}
}
This is a part of my login class:
function process_login(){
global $mysql_prefix;
$email = mysql_real_escape_string($_POST['email']);
$check = mysql_query("SELECT password,salt,id FROM ".$mysql_prefix."users WHERE email='$email'");
if(mysql_num_rows($check) > 0){
$info = mysql_fetch_assoc($check);
$private_key = $this->get_secret_key();
$password = hash('sha256', $info['salt'] . hash('sha256', $private_key.$_POST['password']));
if($password == $info['password']){
$_SESSION[$this->user_session]['id'] = $info['id'];
return true;
}else{
return false;
}
}else{
return false;
}
}
I have required the session class in my global.php file and called the class (or whatever it is called), but how do I actually go about and use this new database session system with my current login class?
I tried to use $ManageSessions->write(id, data) like this:
function process_login(){
global $mysql_prefix;
$email = mysql_real_escape_string($_POST['email']);
$check = mysql_query("SELECT password,salt,id FROM ".$mysql_prefix."users WHERE email='$email'");
if(mysql_num_rows($check) > 0){
$info = mysql_fetch_assoc($check);
$private_key = $this->get_secret_key();
$password = hash('sha256', $info['salt'] . hash('sha256', $private_key.$_POST['password']));
if($password == $info['password']){
$SessionManager->write(session_id(),$info['id']);
return true;
}else{
return false;
}
}else{
return false;
}
}
But it does not seem to work, and the data is overwritten the second the page is updated.
I must be missing something obvious, or just coding something wrong.
(I am aware of the security flaws in the script and I am in the process of redesigning it, so please don't say anything about security or like. Thanks :))
The class above substitutes php's session system with the one in the class. When you make a new instance of the class, its constructor (the function SessionManager() {) is called, setting the functions in the class to run instead of php's defaults. So now when you write something to the $_SESSION, it uses SessionManager's write functions, which adds it to the database.
So basically, just initialize that class on every page, and then use your sessions like you normally would. They'll all just show up in the database.

How can I implement a voting system on my site limiting votes to a single vote?

I am trying to build a site with news links that can be voted, I have the following code:
case 'vote':
require_once('auth/auth.php');
if(Auth::isUserLoggedIn())
{
require_once('data/article.php');
require_once('includes/helpers.php');
$id = isset($_GET['param'])? $_GET['param'] : 0;
if($id > 0)
{
$article = Article::getById($id);
$article->vote();
$article->calculateRanking();
}
if(!isset($_SESSION)) session_start();
redirectTo($_SESSION['action'], $_SESSION['param']);
}
else
{
Auth::redirectToLogin();
}
break;
The problem right now is how to check so the same user does not vote twice, here is the article file:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
require_once(SITE_ROOT.'data/model.php');
require_once(SITE_ROOT.'data/comment.php');
class Article extends Model
{
private $id;
private $user_id;
private $url;
private $title;
private $description;
private $ranking;
private $points;
function __construct($title = ' ', $description = ' ', $url = ' ', $username = ' ', $created = ' ', $modified = '') {
$this->setId(0);
$this->setCreated($created);
$this->setModified($modified);
$this->setUsername($username);
$this->setUrl($url);
$this->setTitle($title);
$this->setDescription($description);
$this->setRanking(0.0);
$this->setPoints(1);
}
function getId(){
return $this->id;
}
private function setId($value){
$this->id = $value;
}
function getUsername(){
return $this->username;
}
function setUsername($value){
$this->username = $value;
}
function getUrl(){
return $this->url;
}
function setUrl($value){
$this->url = $value;
}
function getTitle()
{
return $this->title;
}
function setTitle($value) {
$this->title = $value;
}
function getDescription() {
return $this->description;
}
function setDescription($value)
{
$this->description = $value;
}
function getPoints()
{
return $this->points;
}
function setPoints($value)
{
$this->points = $value;
}
function getRanking()
{
return $this->ranking;
}
function setRanking($value)
{
$this->ranking = $value;
}
function calculateRanking()
{
$created = $this->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
$time = $diff['days'] * 24;
$time += $diff['hours'];
$time += ($diff['minutes'] / 60);
$time += (($diff['seconds'] / 60)/60);
$base = $time + 2;
$this->ranking = ($this->points - 1) / pow($base, 1.5);
$this->save();
}
function vote()
{
$this->points++;
$this->save();
}
function getUrlDomain()
{
/* We extract the domain from the URL
* using the following regex pattern
*/
$url = $this->getUrl();
$matches = array();
if(preg_match('/http:\/\/(.+?)\//', $url, $matches))
{
return $matches[1];
}
else
{
return $url;
}
}
function getTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo( "Ending date/time is earlier than the start date/time");
}
}
else
{
echo( "Invalid date/time data detected");
}
return( false );
}
function getElapsedDateTime()
{
$db = null;
$record = null;
$record = Article::getById($this->id);
$created = $record->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
//echo 'new date is '.date('F d, Y h:i:s A');
//print_r($diff);
if($diff['days'] > 0 )
{
return sprintf("hace %d dias", $diff['days']);
}
else if($diff['hours'] > 0 )
{
return sprintf("hace %d horas", $diff['hours']);
}
else if($diff['minutes'] > 0 )
{
return sprintf("hace %d minutos", $diff['minutes']);
}
else
{
return sprintf("hace %d segundos", $diff['seconds']);
}
}
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
throw $e;
}
}
function delete()
{
try
{
$db = parent::getConnection();
if($this->id != 0)
{ ;
/*$comments = $this->getAllComments();
foreach($comments as $comment)
{
$comment->delete();
}*/
$this->deleteAllComments();
$query = "delete from articles where id = $this->id";
}
parent::execSql($query);
}
catch(Exception $e){
throw $e;
}
}
static function getAll($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$db = null;
$results = null;
$records = array();
$query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions";
try
{
$db = parent::getConnection();
$results = parent::execSql($query);
while($row = $results->fetch_assoc())
{
$r_id = $row['id'];
$r_created = $row['created'];
$r_modified = $row['modified'];
$r_title = $row['title'];
$r_description = $row['description'];
if(!get_magic_quotes_gpc())
{
$r_title = stripslashes($r_title);
$r_description = stripslashes($r_description);
}
$r_url = $row['url'];
$r_username = $row['username'];
$r_points = $row['points'];
$r_ranking = $row['ranking'];
$article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified);
$article->id = $r_id;
$article->points = $r_points;
$article->ranking = $r_ranking;
$records[] = $article;
}
parent::closeConnection($db);
}
catch(Exception $e)
{
throw $e;
}
return $records;
}
static function getById($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select id, username, created, modified, title, url, description, points, ranking from articles where id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Record not found', EX_RECORD_NOT_FOUND);
}
$row = $results->fetch_assoc();
parent::closeConnection($db);
if(!get_magic_quotes_gpc())
{
$row['title'] = stripslashes($row['title']);
$row['description'] = stripslashes($row['description']);
}
$article = new Article($row['title'], $row['description'], $row['url'], $row['username'], $row['created'], $row['modified']);
$article->id = $row['id'];
$article->points = $row['points'];
$article->ranking = $row['ranking'];
return $article;
}
catch (Exception $e){
throw $e;
}
}
static function getNumberOfComments($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select count(*) as 'total' from comments where article_id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Comments Count Query Query Failed', EX_QUERY_FAILED);
}
$row = $results->fetch_assoc();
$total = $row['total'];
parent::closeConnection($db);
return $total;
}
catch (Exception $e){
throw $e;
}
}
function deleteAllComments()
{/*
* Return one record from the database by its id */
$db = null;
try
{
$db = parent::getConnection();
$query = "delete from comments where article_id = $this->id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Deletion Query Failed', EX_QUERY_FAILED);
}
parent::closeConnection($db);
}
catch (Exception $e){
throw $e;
}
}
function getAllComments($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$conditions = "where article_id = $this->id";
$comments = Comment::getAll($conditions);
return $comments;
}
static function getTestData($url)
{
$page = file_get_contents($url);
}
}
?>
Any suggestion or comment is appreciated, Thanks.
make another table user_votes for example with structure:
user_id int not null
article_id int not null
primary key (user_id, article_id)
in vote function first try to insert and if insert is successfull then increase $this->points
Have a table that keeps track of a user's vote for an article (something like UserID,ArticleID,VoteTimeStamp). Then you can just do a check in your $article->vote(); method to make sure the currently logged in user doesn't have any votes for that article.
If you want to keep thing fast (so you don't always have to use a join to get vote counts) you could have a trigger (or custom PHP code) that when adding/removing a vote updates the total vote count you currently keep in the article table.
You have these options:
Track the IP of whoever voted, and store it in a database. This is bad beucase many people might share IP and it can be circumvented using means such as proxies.
Another solution is to store a cookie in the browser. This is probably a bit better than the first solution as it lets many people from the same IP vote. It is, however, also easy to circumvent as you can delete your cookies.
The last and only secure method is to require your users to register to vote. This way you pair username and password against the votes and can ensure everyone votes only once, unless they are allowed to have several users.
A last solution might be a combination of the first two solutions, it is still obstructable though.
You could have a table containing a users ID and the article's ID called something like article_votes. So when user x votes for article y a row is inserted with both ID's. This allows you to check if a user has voted for an article.
To count the number of articles you could use a query like this: SELECT COUNT(*) AS votes FROM article_votes WHERE article=[article id]

Categories