PHP How to make a variable increase after reload - php

What I want to do is to have a variable that increments by 1 after every reload. Now, I can't do cookies because I want it to increment globally, and I've tried sessions but I had no luck with them. If anyone could help me out I'd really appreciate it. I actually can't give any code samples because my tries have turned out very messy.

If you want a variable for each user, then I would definitely go with sessions :
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
} else {
$_SESSION['counter']++;
}
However if you want a unique variable that increases at each load (i.e the same for all users), then you could use a file to store the number of views :
<?php
if(file_exists('counter.txt'))
{
$counter_f = fopen('counter.txt', 'r+');
$count = fgets($counter_f);
}
else
{
$counter_f = fopen('counter.txt', 'a+');
$count = 0;
}
$count++;
fseek($counter_f, 0);
fputs($counter_f, $count);
fclose($counter_f);
?>

Related

Do not increment on page reload

I've placed a hit counter on my page. It reads a text file, increments the number in the file, and later in the page, I output the incremented value.
$hitsFile = "hits/exps/stats.txt";
$hits = file($hitsFile);
$hits[0]++;
$fp = fopen($hitsFile , "w");
flock($fh, LOCK_EX);
fwrite($fp , $hits[0]);
fclose($fp);
My problem is that if I reload the page, the code will increment the hits. I don't want that. I thought of using session to fix that, but with session, in order the increment the hits again, I need to exit the site and visit again. I don't want that either.
I want it to increment not when I reload the page but when I revisit the page.
For example, let's say I have two-page website, Home and Contact, and on contact page I have a hit counter. I don't want the hit counter to increment if I reload(refresh) the contact page, but if I leave the contact page and visit homepage, and later revisit the contact page, I want it to increment.
In short, I don't want it to increment on page reload. Is there a way to do that?
In each of your pages, you need to write the page name in the session.
Do something like this:
$_SESSION['page'] = 'contact';
On the pages where you need to count hits, you need to check this session key.
For example, if you were on page 'contact', then $_SESSION['page'] == 'contact'.
Now when you go to visit the 'homepage':
$page = $_SESSION['page'];
if($page != 'homepage')
{
//increment your hits counter
$_SESSION['page'] = 'homepage';
}
I suggest this method, is my preferred, create in root these folders: cnt and log... then put inside cnt folder the following files cnt.php and showcnt.php...
cnt.php
<?php
##############################################################################
# Php Counter With Advanced Technology For The Prevention Of Reloading Pages #
# Version: 1.4 - Date: 13.11.2014 - Created By Alessandro Marinuzzi [Alecos] #
##############################################################################
function cnt($file) {
session_start();
global $pagecnt;
$reloaded = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
$thispage = basename($_SERVER['SCRIPT_FILENAME']);
if (!isset($_SESSION['first_go'])) {
$_SESSION['first_go'] = 1;
$first_go = TRUE;
} else {
$first_go = FALSE;
}
if (!isset($_SESSION['thispage'])) {
$_SESSION['thispage'] = $thispage;
}
if ($_SESSION['thispage'] != $thispage) {
$_SESSION['thispage'] = $thispage;
$new_page = TRUE;
} else {
$new_page = FALSE;
}
$pagecnt = rtrim(file_get_contents($file));
if ((!$reloaded) && ($new_page == TRUE) || ($first_go == TRUE)) {
$fd = fopen($file, 'w+');
flock($fd, LOCK_EX);
fwrite($fd, ++$pagecnt);
flock($fd, LOCK_UN);
fclose($fd);
}
}
?>
showcnt.php
<?php
##############################################################################
# Show Counter Results - v.1.4 - 13.11.2014 By Alessandro Marinuzzi [Alecos] #
##############################################################################
function gfxcnt($file) {
global $number;
$number = rtrim(file_get_contents($file));
$lenght = strlen($number);
$gfxcnt = "";
for ($i = 0; $i < $lenght; $i++) {
$gfxcnt .= $number[$i];
}
$gfxind = "<span class=\"counter\"><span class=\"number\">$gfxcnt</span></span>";
echo $gfxind;
}
?>
Well, then edit your index.php or other php page... and put at the beginning this piece of code:
<?php session_start(); include("cnt/cnt.php"); cnt("log/index.txt"); include("cnt/showcnt.php"); ?>
Well, then edit index.php or other php page... and use this piece of code for reading counter file:
<?php gfxcnt("log/index.txt"); ?>
It's all, I hope you'll find my answer useful :) My counter can write/read multiple php pages...
Source: my blog (https://www.alecos.it/new/101/101.php)
Add session_start(); to the top.
Now change your if to this:
if (!isset($_SESSION['lastpage']) || $_SESSION['lastpage'] != $_SERVER['QUERY_STRING') {
$hits[0]++;
}
$_SESSION['lastpage'] = $_SERVER['QUERY_STRING'];
This will basically force someone to move to another page if they want to increment the counter.
Update the hit count only if the current URL is not stored in $_SESSION['url'].
After updating the hit count, store the current URL in $_SESSION['url'].

Not able to maintain values in session

Not able to maintain values in session at the client side(Member login).
In the code below, we had stored client id in a session variable. But we can’t access that in myprofile.php. So after login, we can’t maintain myprofile page.
What could be the error?
case "LOGIN":
{
$username = $_REQUEST['a0'];
$password = md5($_REQUEST['a1']);
$table_name = "coco_members";
$count = $fn->returnColumn($table_name,"count(*) as val","member_uname='$username' and member_pwd='$password' and member_active='1'");
if($count>0)
{
$result = $fn->returnColumn($table_name,"member_id","member_uname='$username' and member_pwd='$password' and member_active='1'");
}
else
{
$result ="";
}
if($result!="")
{
$_SESSION['CID'] = $result;
echo $_SESSION['CID'];
}
else
{
$_SESSION['CID']="";
echo "NOK";
}
break;
}
case "GETPOSTS":
{
$page = $_REQUEST['page'];
$activeid = $_REQUEST['id'];
$count = $_REQUEST['count'];
include("includes/client.php");
echo getPosts($page,$activeid,$count);
break;`
I also had some problems with sessions at some servers. In XAMP it would work prefect but when transferred on server it would not recognize session. Finally I find solution for this, by trails and errors. By creating session.php file and including it at the top of all files that needed session. Just write session_start(); in session.php and that is all.
Dunno if this will help you but it helped me while working on few project that had servers who wouldn't do what they needed to.
EDIT: In 90% percent of my cases, that had this problem, where on free servers so if your working on free server this might fix it.

session_start() error: why it doesn´t recognize a new session?

I´m testing a php exercise, and I can´t get it working properly. It´s a counter that stores the visits inside a txt file as a simple integer. Every time I reload the page the number gets a +1.
Now, I want it to reload only when there´s a new visit, so I´m trying sesion_start() for the first time.
In class, this example worked just fine, but when I try to reproduce it at home, the number won´t change, even if I close the browser and open it again.
This is my code (it´s inside the php tags, naturally):
session_start();
if (!$_SESSION[contador]) {
define('ARCHIVO', 'visitas.txt');
if (file_exists(ARCHIVO)) {
$fp=fopen(ARCHIVO, 'r');
$cant=fread($fp,filesize(ARCHIVO));
fclose($fp);
} else {
$cant=0;
}
$cant++;
$fp=fopen(ARCHIVO, 'w');
fwrite($fp, $cant);
fclose($fp);
$_SESSION[contador]=$cant;
}
echo '<h3>Hay '.$_SESSION[contador].' visitas.</h3>';
contador should be in quotes unless it's a defined constant somewhere?? I assume it's a string
$_SESSION["contador"]
Try this out. It's different, but it'll do something at least. Would've posted as a comment, but I wanted code formatting.
session_start();
if(empty($_SESSION['contador'])){
$_SESSION['contador']=1;
}else{
$_SESSION['contador']++;
}
echo '<h3>Hay '.$_SESSION['contador'].' visitas.</h3>';
First of all, #Lenny is correct. $_SESSION['contador'] is what is called a session variable or a variable assigned to the $_SESSION array. So it MUST BE in quotes. That is not optional. And you cannot define a constant and use that value inside the brackets.
if you had a constant, you could set the session variable to that. But, since your value is variable, as you are adding incrementally, it is by definition not constant.
Furthermore, refreshing your Web browser will keep your session active. So if you truly want to test this, try session_destroy(); at some point.
Here is how this code will work (the storage of the session variable anyway):
<?php
session_start();
if(!isset($_SESSION['contador'])) {
define('ARCHIVO', 'visitas.txt');
if(file_exists(ARCHIVO)) {
$fp = fopen(ARCHIVO, 'r');
$cant = fread($fp,filesize(ARCHIVO));
fclose($fp);
} else {
$cant=0;
}
$cant++;
$fp = fopen(ARCHIVO, 'w');
fwrite($fp, $cant);
fclose($fp);
$_SESSION['contador'] = $cant;
}
echo '<h3>Hay ' . $_SESSION['contador'] . ' visitas.</h3>';
?>
Note: your logic is bad. Your are telling your script that $cant is either equal to the value of the txt file OR it is equal to 0. Then your are incrementing that value by one. You will perform that task on each load. You need to modify this code and finish your conditional statement.
<?php
session_start();
if(!isset($_SESSION['contador'])) {
define('ARCHIVO', 'visitas.txt');
if(file_exists(ARCHIVO)) {
$fp = fopen(ARCHIVO, 'r');
$cant = fread($fp,filesize(ARCHIVO));
fclose($fp);
} else {
$cant=0;
}
$cant++;
$fp = fopen(ARCHIVO, 'w');
fwrite($fp, $cant);
fclose($fp);
$_SESSION['contador'] = $cant;
} else {
$_SESSION['contador']++;
}
echo '<h3>Hay ' . $_SESSION['contador'] . ' visitas.</h3>';
?>
I hope this helps.

preventing multi refresh to count on stats script

i am working on a project which one of our web application would be somehow JavaScript code to gather statistical information about visitors but as far as i know on server side PHP application i should somehow handle the code in a way that multi refresh doesn't count and counting on IP based is not a good idea since many users may have the same IP , cookie or session are also vulnerable to this issue because cookie manager can just wipe out all the cookie related to the site so PHP won't recognize the user and count it new,timeframe jobs and all other way to get-around of this issue are also as far as i know based on cookie or session or ip or a mixture of ip/referrer and all other available data from header, how can i handle it and get more reliable data from users and don't permit them to create fake stats. as i believe there must be a way (i hope so)...!?
I think cookies would be ideal for this kind of problem, but if you do not want to use that then you've got yourself a tough cookie. Unfortunately you don't have many other options since HTTP is stateless.
I would use session vars in this case since the user cannot meddle with the data saved there. There is however the risk of session hijacking, but if your site is open to that vulnerability you need to look at securing the site on a more global level that just the hit counter. The session variable is bound to your site since the data in it is saved on the server rather than in the users browser. And is bound to your user since it saves a cookie with a key in the users browser to request the data from the server.
Here is an example on how you can implement this and not worry about deleting other sessions on the site.
<?php
function hit_counter() {
if(isset($_SESSION['hit_counter'])) { // Check if the user has the hit_counter session
if(isset($_SESSION['hit_counter']['time']) && isset($_SESSION['hit_counter']['page'])) { // Check if the user has the time and the page set from the last visit
$last_time = $_SESSION['hit_counter']['time'];
$last_page = $_SESSION['hit_counter']['page'];
$now = time(); // The current UNIX time stamp in seconds
$current_page = $_SERVER['REQUEST_URI']; // The page name
/*
If the users hasn't requested this page
in the last 10 seconds or if the user
comes from another page increment the
hit counter
*/
if(($now - $last_time) > 10 || $last_page != $current_page) {
/* INCREMENT YOUR HIT COUNTER HERE */
}
}
unset($_SESSION['hit_counter']); // Delete this hit counter session
}
// And create a new hit counter session
$_SESSION['hit_counter'] = array();
$_SESSION['hit_counter']['time'] = time();
$_SESSION['hit_counter']['page'] = $_SERVER['REQUEST_URI'];
}
?>
You will never touch any of the other session variables since you're only unset()ing the hit counter variable. There is no need for you to handle session_destroy(), but you need to make sure that there is a session_start() in the beginning of every page you would like to use function in.
You could edit the script to not factor in time if you'd only want to count hits if the user comes from another page on your site.
This is as far as I can see, a hit counter with a sensible level of security for most sites. Or at the very least a good start.
Some more information about PHP sessions.
I created this
<?php
namespace Codelaby\EventDateGenerator;
class CounterVisitors
{
private $filename = "counter.txt";
private $sessionId;
private $sessionStart;
public function __construct()
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['sessionId'])) {
$this->sessionId = md5(uniqid(rand(), true));
$_SESSION['sessionId'] = $this->sessionId;
$this->sessionStart = time();
$this->hitCounter();
} else {
$this->sessionId = $_SESSION['sessionId'];
if (!isset($_SESSION['sessionStart'])) {
$this->sessionStart = time();
} else {
$this->sessionStart = $_SESSION['sessionStart'];
}
if (time() - $this->sessionStart > 60) {
$this->sessionStart = time();
$this->hitCounter();
}
}
$_SESSION['sessionStart'] = $this->sessionStart;
}
private function saveCounter($counter = 0)
{
if (!file_exists($this->filename)) {
touch($this->filename);
}
$fp = fopen($this->filename, "w");
if (!flock($fp, LOCK_EX)) {
return;
}
fwrite($fp, $counter);
flock($fp, LOCK_UN);
fclose($fp);
}
public function readCounter()
{
if (!file_exists($this->filename)) {
touch($this->filename);
}
$fp = fopen($this->filename, "r");
if (!flock($fp, LOCK_EX)) {
return;
}
$file_size = filesize($this->filename);
if ($file_size <= 0) {
$counter = 0;
} else {
$counter = intval(fread($fp, $file_size));
}
flock($fp, LOCK_UN);
fclose($fp);
return $counter;
}
public function hitCounter()
{
$counter = $this->readCounter();
$counter++;
$this->saveCounter($counter);
return $counter;
}
public function resetCounter($counter = 0)
{
$this->saveCounter(0);
}
}
How to use
session_start() //before send headers
$counterVisitors = new CounterVisitors();
$visitors = $counterVisitors->readCounter();
echo 'visitors: ' . $visitors;
The script generate counter.txt if not exist, only increment visit if user start new session or wait 60 seconds for refresh

How to skip a statement execution from the second time if I call the same page again in PHP

In my temp_file.php i have a variable (array)
<?php
$temp = array();
?>
No in my currentPage.php i am using this
<?PHP
include 'temp_file.php';
///giving some value to $id and calling same page again
array_push($GLOBALS['temp'],$id);
?>
I want to use this temp array to append a value each time i call the same file(CurrentPage.php) but include 'temp_file.php'; statement is executing every time and i am getting single element to my array that i was last pushed.
Can any one help me is there any way in php to skip this include statement from second time to till the session end.
Since you mention sessions in your question, you must know about them. Then, why don't you store $temp variable in session, like:
$_SESSION['temp'] = $temp?
This is what you need ?
<?PHP
session_start();
if (!isset($_SESSION['temp']) {
$_SESSION['temp'] = array($id);
} else {
$_SESSION['temp'][] = $id;
}
$f = array_count_values($_SESSION['temp']);
if ($f[$id] < $Limit) {
include 'temp_file.php';
} else {
// Error
}
?>
You can store your array in $_SESSION, so your temp_file.php will become:
<?php
if(!$_SESSION['temp']) {
$_SESSION['temp'] = array();
}
?>
and your current page like this:
<?php
include 'temp_file.php';
array_push($_SESSION['temp'],$id);
?>
And you have to be careful to destroy your session variables when it ends.
None of the answers are correct.
include_once() will not work for you, as you will be loading the page again, even if it is the second time, as with every load the php will execute from the top.
Because include_once() will only stop the redundant inclusion in same execution, not multiple.
Here is a simple workaround to your problem
<?PHP
if(!isset($_SESSION['include']) || !$_SESSION['included'])) {
// ^ Check if it was included before, if not then include it
include 'temp_file.php';
$_SESSION['included'] = true; //set a session so that this part never runs again for the active user session
}
///giving some value to $id and calling same page again
array_push($GLOBALS['temp'],$id);
?>
<?PHP
if (!isset($GLOBALS['included_temp_file']) || $GLOBALS['included_temp_file'] != true) {
include_once 'temp_file.php';
$GLOBALS['included_temp_file'] = true;
}
///giving some value to $id and calling same page again
array_push($GLOBALS['temp'],$id);
?>

Categories