Creating hit Counter - php

I am trying to create a hit counter for my website and I have developed the following code for it. I have included the following code only in Codeigniter's main controller for my home page.
At first I thought the code was working fine but I just found that if I don't keep on browsing the pages then again go to the home page it doesn't update the data. I mean for example: If I go to my homepage for the first time then it updates the data, but after 10 seconds if I refresh the page it does't update the data. But if I keep refreshing it for 10 seconds then it works.
So could you please tell me how to get it update the data without having to keep on browsing the pages or refreshing the home page?
Thanks :)
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout')) {
$out = time() + 10; // I will change it to $out = time() + 60*60; later
$this->session->set_userdata('timeout', $out);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat+1
WHERE id = '1'");
} else {
$timeout_time = $this->session->userdata('timeout');
if (time() > $timeout_time) {
$this->session->set_userdata(array('timeout' => ''));
$this->session->sess_destroy();
}
}
}
edit
What I am trying to achieve is when an user visits the webpage for the first time, I want to update my database. Within 10 seconds (for example purpose), if the visitor again visits the home page, the database will not be updated. But after 10 seconds if he again visits the home page, I want to update my database.
Thanks :)

Your code says "if there is no timeout in the session, update the count". You want it to say "if there is no timeout in the session, or there is but it's old, update the count".
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout') || $this->session->userdata('timeout') < time()) {
$this->session->set_userdata('timeout', time() + 10);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat + 1 WHERE id = 1");
}
}
I'm not a CodeIgniter user, so I am assuming that you used its session facilities correctly; I just used them the same way.

Related

Prevent user from entering page again after logout

I've created this code so that the user will not redirect onto the next page again. I set the maximum value on votenow button to 1 and once the user click the button again the value on the votenow button will not be added anymore since its maximum is 1. Everything works fine except that the user can still access the nextpage though the maximum value on the button was reached. Here's the code.
<?php
$errors = array();
$db = mysqli_connect("localhost","root","","registration");
if(isset($_POST['votenow']))
{
$votenow ="0";
$votenow1="1";
if($votenow != $votenow1){
$votenow = "update users set votenow = votenow + 1 WHERE votenow=0 LIMIT 1 ";
$run_vote = mysqli_query($db,$votenow);
echo '<script type="text/javascript">alert("hello!");</script>';
header ("Refresh:2; url=renewsys3.php");
}
else{
echo '<script type="text/javascript">alert("oh not again!");</script>';
header ("Refresh:2; url=renewsys2re.php");
}
}
?>
Can you guys help me or is there any other way so that the user will not enter the next page again? Btw, this is a voting system
The best way to use session:
$_SESSION['votenow'] = 0;
if (isset($_SESSION['votenow'])) {
if (!$_SESSION['votenow']) {
//do something
} else { // means $_SESSION['votenow'] == 1
// do something else
}
}
Redirect the URL to a different page (maybe homepage or any page) If the maximum vote is reached.
Let that code run before any other code so that the page won't load of the condition is true. It'll redirect immediately.

How to prevent the user from abusing a button?

i'm quite a beginner with PHP and i tried to make something to get xp when cliking the button. You just need to click and it gives xp, then it refresh the page to refresh the player's stat on screen.
<form method="post">
<p><input type="submit" value="Kill the mob" name="add20xp" /></p>
</form>
<?php
if (isset($_POST['add20xp']))
{
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
?>
The problem is that i want to prevent the user from smashing the button to prevent bugs and things like that... I tried to put sleep(1) but i can just keep spamming, wait the seconds and it works so it's not very useful.
Thanks for the help !
Save the last time the update was done in session state. Then, only allow the button to be pressed after (last time + 2 seconds) (Two seconds was chosen since that was the suggested interval in your original question).
if (isset($_POST['add20xp'])) {
if (!isset($_SESSION['last_post'])) {
$_SESSION['last_post'] = 0;
}
$currtime = time();
if ($currtime > ($_SESSION['last_post'] + 2)) {
$_SESSION['last_post'] = $currtime;
// ... process the post.
$add20xp =("UPDATE users SET exp = (exp + 20)"); // fix this line
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
}
As #Martin noted above in his comment, you want to do the update only for the user who pressed the button, which is the meaning of the comment "fix this line."
If you want to disable the button for 3 seconds after the form is submitted you can use this:
if(sessionStogare.getItem('submitted') === true){
document.querySelector('input[type="submit"]').disabled = true;
setTimeout(function(){
document.querySelector('input[type="submit"]').disabled = false;
sessionStorage.removeItem("submitted");
}, 3000);
}
document.querySelector("body").onclick = function() {
sessionStorage.setItem("submitted", true);
};
We will note the submission in the sessionStorage and check, if the form has been submitted every time we load the page. Then, we will disable the button and enable it after 3 seconds.
Change your php page to this:
// the beginning of the page:
<?php
// start a SESSION
session_start();
// setup a $_SESSION variable
if (!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
//
// now put the $_POST part
if (isset($_POST['add20xp'])) {
// check the time
$now = time();
if ($now - $_SESSION["timestamp"] > 2) {
// more than 2 seconds have passed since last $_POST
// update the time
$_SESSION["timestamp"] = time();
//
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
//
echo '<meta http-equiv="refresh" content="0.1" />';
exit;
} else {
// nothing, just let the page load like it is.
}
}
?>
Notice some important changes:
the use of $_SESSION vars -> these vars are stored and can be
retrieved at every page load -> you can use them to store the last
time an action took place
the $_POST part should be at the beginning
of the page -> otherwise after you send a form, you load the page ->
check the post -> then reload... it's not efficient
if you put the $_POST part at the beginning, you actually don't need the page reload with the meta tag -> because the data are already
updated

how can i track last 5 pages visited using cookies in php

<?php
session_start();
if(empty($_SESSION['track']))
$_SESSION['history'] = array($_SERVER['PHP_SELF']);
else {
$_SESSION['track'][] = $_SERVER['PHP_SELF'];
if(count($_SESSION['track']) > 5)
array_shift($_SESSION['track']);
}
function display()
{
print_r(array_values($_SESSION['track']));
}
?>
i was able to do it using session but i need to use only cookies and php to track the last 5 pages visited.
any idea guys??
Any comment or answer will appreciate. Thanking in advance.
$url = unserialize($_COOKIE['history']);
array_push($url,your_url);
setcookie('history', serialize($url));
onload of every page first retrieve the value of cookie in url and push the current url in it and add set it to cookie

php sessions that counts page refereshes dynmically

my code is related to breadcrumbs.. that is it should display previous page or from where it is navigated and i achieved it partially , while im refreshing 2-3 times im getting the current page not the previous page.. so pl help me on this
my code lies in session.php as
$add = $_SERVER['PHP_SELF'];
if($_SESSION['pageadd'][1]!= $_SESSION['pageadd'][2])
{ $_SESSION['pageadd'][2]= $_SESSION['pageadd'][1];
}
echo $_SESSION['pageadd'][2];
if(($_SESSION['pageadd'][1]!= $add) )
{ $_SESSION['pageadd'][1]= $_SESSION['pageadd'][0];
$_SESSION['pageadd'][0]=$add;
}
What you want isn't a breadcrumb - it's a history for visited pages! This could be achieved with something like this:
if (!isset($_SESSION['pageadd'])) {
$_SESSION['pageadd'] = array();
}
// add page
$_SESSION['pageadd'][] = $_SERVER['PHP_SELF']
// only save last 5 pages
if (count($_SESSION['pageadd'])) > 5) {
array_shift($_SESSION['pageadd']);
}
Try to use $_SERVER['HTTP_REFERER'] it will return you previous url. However you need to store it in some hidden field or session like you are doing now.
Hope this help :)

PHP auto-logout after 10 mins of inactivity

Currently I'm tracking time spent by user on website using PHP code mentioned below:
if (!isset($_SESSION[timeset1]))
{
$one_val = time();
$_SESSION[timeset_dummy]= $one_val;
$two_val = time()+1;
$_SESSION[units_all] = array
(
"year" => 29030400,
"month" => 2419200,
"week" => 604800,
"day" => 86400,
"hr" => 3600,
"min" => 60,
"sec" => 1
);
}
else
{
$two_val = time();
}
$diff = abs($two_val - $_SESSION[timeset_dummy]);
foreach($_SESSION[units_all] as $unit => $mult)
if($diff >= $mult)
{
$output .= " ".intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
I want to give pop-up to users after 8 mins of inactivity that session will expire in next 2 mins. Can you please suggest how can I show pop-up (preferably without using Javascript, nice to have with CSS3 & HTML5) . Pop-Up will have warning message "Do you want to continue" and one button "Yes" , if button is not clicked for 2 mins automatically page logout script (PHP) will be executed.
Any pointers to to get this logic implemented.
I found a jQuery plugin that looks like it will make your life easier. It is called jquery-idleTimeout.
The plugin has a few configuration items so you can customize it for your own needs…
inactivity: 1200000 //20 Minute default (how long before showing the notice)
sessionAlive: 300000, //5 minutes default how often to hit alive_url, we use for our ajax * interfaces where the page doesn’t change very often. This helps to prevent the logout screen of your app appearing in ajax callbacks. If you set this to false it won’t send off.
alive_url: ‘/path/to/your/imHere/url’, //send alive ping to this url
redirect_url: ‘/js_sandbox/’, //Where to go when log out
click_reset: true, //Reset timeout on clicks (for ajax interface) – resets the sessionAlive timer, so we are not hitting up your app with alive_url if we just did an ajax call for another reason.
logout_url: ‘/js_sandbox/timedLogout/index.html’ //logout before redirect (url so you can completely destroy the session before redirecting to login screen)
Here is a link to the github page to download the library.
https://github.com/philpalmieri/jquery-idleTimeout
Edit
Something I also noticed while looking at the source code, they are using jquery-ui as their stylesheet to make it look like it does in the demo.
As far as I know, you cannot achieve what you are looking for without javascript. The browser needs javascript to know when to open the pop-up. You can use whatever means you want to check for timeout, either the basic window.setTimeout or a more advanced library (like the one in tehAon's answer).
Since I cannot post a comment I'm going to ask here: your code seems awfully complicated for checking if a user is still active. Is there any particular reason you could not use something like this:
$_SESSION['last_activity'] = time();
function check_if_logged_in() {
if(time() - $_SESSION['last_activity'] > 600) { // 10 minutes but you could use 480 for 8 minutes
// Do redirect or take other action here
}
}
if(time() - $_SESSION['timestamp'] > 900) { //15 minute subtract new timestamp from the old one
$_SESSION['logged_in'] = false;
session_destroy();
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
This is quite easy with php session variable.
set $_SESSION variable with timestamp and check with the action time
<?php
session_start();
if(time()-$_SESSION['time']>600)
unset($_SESSION['time']);
else
$_SESSION['time']=time();//updating with latest timestamp
?>

Categories