I Want to get the page count using cookie - php

I want to get the page count in my index page,using cookie.So far I have done like.Now My question is:If I refresh the page, The browser shows with count 2 and it doesnot increase for next refresh.I don't know what is wrong in my code.Further I want to know how to handle cookie in next page or shall I can handle cookie in same page? can any one guide please.but this is my requirement.
<?php
$cookie = 1;
setcookie("count", $cookie);
if (!isset($_COOKIE['count']))
{
}
else
{
$cookie = ++$_COOKIE['count'];
}
echo "The Total visit is".$cookie;
?>

I decided to use local storage for this as I really dislike cookies, some users block them completely.
You can setup the echo. To work with this
Here is what I cam up with: http://jsfiddle.net/azrmno86/
// Check browser support
if (typeof(Storage) != "undefined") {
//check if the user already has visited
if (localStorage.getItem("count") === "undefined") {
//set the first time if it dfoes not exisit yet
localStorage.setItem("count", "1");
}
//get current count
var count = localStorage.getItem("count");
//increment count by 1
count++;
//set new value to storage
localStorage.setItem("count", count);
//display value
document.getElementById("result").innerHTML = count
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support";
}
UPDATE After a bit more clarification
This style uses a .txt file stored on the server. Cookies are not reliable. If someone clears them, your done. if you use variables any server restart will kill your count. Eith use database or this method.
<?php
//very important
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
echo "You are visitor number $counterVal to this site";

Related

simple php page session visit counter not working

I am having this strange issue and can't figure it out.
On some websites I have this script works perfect... same code, same server settings...
With php, there is a simple page view hit counter that stores locally in a txt file.
Then I echo out the value on the footer copyright area of my websites to give the client a quick statistic... its pretty cool how fast it grows.
Anyway.. i have a client corner grill ny . com (seo purposes I added spaces )
On that website.. its been working great for years.
Now another website and a bunch more.. for example... savianos . com
This breaks.. and the text value is blank.
This is the counter.php code
<?php
session_start();
$counter_name = "counter/hits.txt";
//Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
$f = fopen($counter_name, "w");
fwrite($f,"0");
fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
$_SESSION['hasVisited']="yes";
$counterVal++;
$f = fopen($counter_name, "w");
fwrite($f, $counterVal);
fclose($f);
}
?>
Now, if I add a value in the txt file.. like 1040... and go to the website it starts to work... then after a week or so I check it .. its blank again.
Any ideas?
I am thinking that this may be happening because the website might get a TON of views during dinner time friday night.. and the simple script can't handle it so.. while its trying to write a added a number it just breaks and go to blank.. and never starts back up again.
The structure is this.
/counter/ folder has
counter.php and a hits.txt file
Every page of the website the very first thing is
<?php include ('counter/counter.php'); ?>
and in the footer of the website we have
<?php echo $counterVal; ?>
Your code looks perfect, but let's understand the situation. You have a file which can be accessed concurrently for many users, because page visit can be done by multiple users on same time. This does't seem right you have to lock the file manipulation for another user while someone is modifying it, right?. Please have a look
Visits counter without database with PHP
It is most likely because you have two concurrent scripts that tried to open the file at one and one of them fail. You have to use flock() when there are multiple instances of the script that could operate at the same time. Counter are some of the heaviest things if you going to use file reading and writing. I wrote this wrapper to easily implement file locking.
If you want to check out one of my counters that in operation try http://ozlu.org. That dynamic counter image was self-built. The fileReadAll will read the entire file in one shot. The file writer only has two modes, write or append. You can pass the fileWriter an array or a string and it will write it to the file. The function will not add any \n to format your text so you would have to add that. The default mode for the fileWriteAll is w if you do not set the third argument.
function fileWriteAll($file, $content, $mode = "w"){
$mode = $mode === "w" || $mode === "a"? $mode : "w";
$FILE = fopen($file, $mode);
while (!flock($FILE, LOCK_EX)) { usleep(1); }
if( is_array($content) ){
for ($i = 0; $i < count($content); $i++){
fwrite($FILE, $content[$i]);
}
} else {
fwrite($FILE, $content);
}
flock($FILE, LOCK_UN);
fclose($FILE);
}
function fileReadAll($file){
$FILE = fopen($file, 'r');
while (!flock($FILE, LOCK_SH)) { usleep(1); }
$content = fread($FILE, filesize($file));
flock($FILE, LOCK_UN);
fclose($FILE);
return $content;
}
Your modified code:
session_start();
$counterName = './views.txt';
if (!file_exists($counterName)) {
$file = fopen($counterName, 'w');
fwrite($file, '0');
fclose($file);
}
$file = fopen($counterName, 'r');
$value = fread($file, filesize($counterName));
fclose($file);
if (! isset($_SESSION['visited'])) {
$_SESSION['visited'] = 'yes';
$value++;
$file = fopen($counterName, 'w');
fwrite($file, $value);
fclose($file);
}
session_unset();
echo $value;

PHP hit Counter text file value resets frequently?

I am Using this simple hit counter script in my website. but its value resets to zero or changes to a lower value frequently (no specific time interval i noticed). is there any problem in scripts. please help ?
<?php
// SETUP YOUR COUNTER
// Detailed information found in the readme.htm file
// Count UNIQUE visitors ONLY? 1 = YES, 0 = NO
$count_unique = 1;
// Number of hours a visitor is considered as "unique"
$unique_hours = 1;
// Minimum number of digits shown (zero-padding). Set to 0 to disable.
$min_digits = 5;
#############################
# DO NOT EDIT BELOW #
#############################
/* Turn error notices off */
error_reporting(E_ALL ^ E_NOTICE);
/* Get page and log file names */
$page = input($_GET['page']) or die('ERROR: Missing page ID');
$logfile = 'logs/' . $page . '.txt';
/* Does the log exist? */
if (file_exists($logfile))
{
/* Get current count */
$count = intval(trim(file_get_contents($logfile))) or $count = 0;
$cname = 'tcount_unique_'.$page;
if ($count_unique==0 || !isset($_COOKIE[$cname]))
{
/* Increase the count by 1 */
$count = $count + 1;
$fp = #fopen($logfile,'w+') or die('ERROR: Can\'t write to the log file ('.$logfile.'), please make sure this file exists and is CHMOD to 666 (rw-rw-rw-)!');
flock($fp, LOCK_EX);
fputs($fp, $count);
flock($fp, LOCK_UN);
fclose($fp);
/* Print the Cookie and P3P compact privacy policy */
header('P3P: CP="NOI NID"');
setcookie($cname, 1, time()+60*60*$unique_hours);
}
/* Is zero-padding enabled? */
if ($min_digits > 0)
{
$count = sprintf('%0'.$min_digits.'s',$count);
}
/* Print out Javascript code and exit */
echo 'document.write(\''.$count.'\');';
exit();
}
else
{
die('ERROR: Invalid log file!');
}
/* This functin handles input parameters making sure nothing dangerous is passed in */
function input($in)
{
$out = htmlentities(stripslashes($in));
$out = str_replace(array('/','\\'), '', $out);
return $out;
}
?>
As far as my assumption, this reset occurs when there are simultaneous visits from users leading bad I/O of file, thus resetting it.
Solution:
Create a timely backup of txt file and compare values to publish the value from the file which has higher counter.
Switch to database!

get specific text from .txt file in php

I am having a log file like this :
2013-04-08-03-17-52: Cleaning Up all data for restart operation
2013-04-08-03-18-02: Creating new instance of app before closing
2013-04-08-03-18-03: New instance created and running
2013-04-08-03-18-03: Application started
Currently, i am loading full log file every second to show it to the user using jquery ajax, As this being soo inefficient i am trying to figure out some way to load only the updated lines from log file.
Is their any way to get lines only after a particular time stamp 2013-04-08-03-18-03
, For this i will be managing a variable with last timestamp and will be updating it every time i get new lines.
I am kind of New to Php and know only the basics of reading and writing files.
You might want to check the file modification time first to see whether or not you need to reload the log file. You can use the filemtime-function for that.
Furthermore, you can use the file_get_contents-function using an offset to read the file from a certain point.
Edit: So, how does it work?
Suppose you have stored the last modification time in a session variable $_SESSION['log_lastmod'] and the most recent offset in $_SESSION['log_offset'].
session_start();
// First, check if the variables exist. If not, create them so that the entire log is read.
if (!isset($_SESSION['log_lastmod']) && !isset($_SESSION['log_offset'])) {
$_SESSION['log_lastmod'] = 0;
$_SESSION['log_offset'] = 0;
}
if (filemtime('log.txt') > $_SESSION['log_lastmod']) {
// read file from offset
$newcontent = file_get_contents('log.txt', NULL, NULL, $_SESSION['log_offset']);
// set new offset (add newly read characters to last offset)
$_SESSION['log_offset'] += strlen($newcontent);
// set new lastmod-time
$_SESSION['log_lastmod'] = filemtime('log.txt');
// manipulate $newcontent here to what you want it to show
} else {
// put whatever should be returned to the client if there are no updates here
}
You can try
session_start();
if (! isset($_SESSION['log'])) {
$log = new stdClass();
$log->timestamp = "2013-04-08-03-18-03";
$log->position = 0;
$log->max = 2;
$_SESSION['log'] = &$log;
} else {
$log = &$_SESSION['log'];
}
$format = "Y-m-d-:g:i:s";
$filename = "log.txt";
// Get last date
$dateLast = DateTime::createFromFormat($format, $log->timestamp);
$fp = fopen($filename, "r");
fseek($fp, $log->position); // prevent loading all file to memory
$output = array();
$i = 0;
while ( $i < $log->max && ! feof($fp) ) {
$content = fgets($fp);
// Check if date is current
if (DateTime::createFromFormat($format, $log->timestamp) < $dateLast)
continue;
$log->position = ftell($fp); // save current position
$log->timestamp = strstr($content, ":", true); // save curren time;
$output[] = $content;
$i ++;
}
fclose($fp);
echo json_encode($output); // send to ajax
Try something like this:
<?php
session_start();
$lines = file(/*Insert logfile path here*/);
if(isset($_SESSION["last_date_stamp"])){
$new_lines = array();
foreach($lines as $line){
// If the date stamp is newer than the session variable, add it to $new_lines
}
$returnLines = array_reverse($newLines); // the reverse is to put the lines in the right order
} else {
$returnLines = $lines;
}
$_SESSION['last_date_stamp'] = /* Insert the most recent date stamp here */;
// return the $returnLines variable
?>
What this does is reads a file line by line and, if a session variable already exists, add all of the lines where the date stamp is newer than the one in the session variable to a return variable $returnLines, if no session variable exists it will put all of the lines in the file in $returnLines.
After this, it create.updates the session variable for use the next time the code is executed. Finally it returns the log file data by using the $returnLines variable.
Hope this helps.

Need help resetting a php counter

I'm really new to php. I decided to make a counter based off a script I've seen. I've made changes to it. I'm trying to figure out how to reset the counter.
$userCount = file_get_contents("count.txt");
$userCount = trim($userCount);
$userCount = $userCount + 1;
$countReset = $userCount - $userCount;
$file = fopen("count.txt","w+");
fwrite($file,$userCount);
fclose($file);
print "The number of visitors is: $userCount";
if ($userCount < 20){
echo 'not yet';
}
else {
echo 'done!';
}
if ($userCount > 40){
fwrite($file,$countReset);
fclose($file);
}
I tried subtracting the counter from itself to get it back to 0.
$countReset = $userCount - $userCount;
However, it doesn't seem to work. the counter itself works, but I am unable to get it to reset back to 0.
This is just an impression like script I'm doing as a way to learn php. Also, sorry about the format, struggling with this post editor.
Any help with the script?
You've closed the file before trying to write to it again. Before your second fwrite, add:
$file = fopen("count.txt","w+");
Try to simply set value 0 to the var:
$countReset = 0;
Couldn't you just edit the count.txt file?
Doing it in PHP, you could do
fwrite($file,'0');
EDIT: Like CanSpice said, you shouldn't close the file before you're done with it. Remove the first fclose, and it should work.
I wouldn't mix fopen() and file_get_content() functions in this context, either use fopen(), fread() and fwrite() or use file_get_contents() and file_put_contents().
If you need just reset counter and you don't need previous value, than use:
file_put_contents('count.txt', '0');
If you need update value you may use either:
$count = file_get_contents( 'count.txt');
$count++;
// Reset?
if( $reset){
$count = 0;
}
file_put_contents( 'count.txt', "$count");
Or rather:
$fp = fopen( 'count.txt', 'r+') or die( 'Cannot use counter');
$count = trim( fread( $fp, 1024));
$count++;
// Reset?
if( $reset){
$count = 0;
}
ftruncate( $fp, 0);
fseek( 0, SEEK_SET)
fwrite( $fp, "$count");
fclose( $fp);
Here are the manual pages for ftruncate() and fseek() + you should probably study flock() so two scripts wouldn't overwrite the content at the same time.
/****************************************************************************
* read the current count from the counter file, increment
* it by 1, and re-save the new value off to the file
***************************************************************************/
function getAndIncrementCount(){
// attempt to open the file
// a+ means keep the contents so we can read it at least once,
// but allow us to overwrite the value once we increment it
if (($fHandle = fopen('count.txt','a+')) !== FALSE){
// read in the count (also cast to an int so if there is
// an invalid (or absent) value it will default to a 0
$count = (int) fread($fHandle, 100);
// increase the counter
$count++;
// go back to the beginning of the file
fseek($fHandle, 0);
// re-write the new count back to the file
fwrite($fHandle, $count);
// cose the file now that we're done with it
fclose($fHandle);
// return back the count
return $count;
}
// we couldn't get to the file, so return an error flag
return FALSE;
}
/****************************************************************************
* write the specified value to the counter file
***************************************************************************/
function setCount($count = 0){
// attempt to open the file with over-write permissions
// w+ will open the file and clear it
if (($fHandle = fopen('count.txt','w+')){
// write the counter to the file
fwrite($fHandle, $count);
// close the file now that we're done
fclose($fHandle);
// return the newly saved count
return $count;
}
// we couldn't get to the file, so return an error flag
return FALSE;
}
And applied in practice:
$userCount = getAndIncrementCount();
echo "The number of visitors is: {$userCount}";
if ($userCount < 20){
echo "Not Yet";
}else{
echo "Done!";
}
if ($userCount > 40){
setCount(0);
}
It's because you are not rewriting the file contents but adding to them when you use the fwrite second time, so $countReset gets appended to the content already in the file. Try this:
$userCount = file_get_contents("count.txt");
$userCount = $userCount + 1;
$countReset = $userCount - $userCount;
file_put_contents("count.txt", $userCount);
print "The number of visitors is: $userCount\n";
if ($userCount < 20){
echo 'not yet';
}
else {
echo 'done!';
}
if ($userCount > 40){
file_put_contents("count.txt", $countReset);
}

file_get_contents create file is not exists

Is there any alternative to file_get_contents that would create the file if it did not exist. I am basically looking for a one line command. I am using it to count download stats for a program. I use this PHP code in the pre-download page:
Download #: <?php $hits = file_get_contents("downloads.txt"); echo $hits; ?>
and then in the download page, I have this.
<?php
function countdownload($filename) {
if (file_exists($filename)) {
$count = file_get_contents($filename);
$handle = fopen($filename, "w") or die("can't open file");
$count = $count + 1;
} else {
$handle = fopen($filename, "w") or die("can't open file");
$count = 0;
}
fwrite($handle, $count);
fclose($handle);
}
$DownloadName = 'SRO.exe';
$Version = '1';
$NameVersion = $DownloadName . $Version;
$Cookie = isset($_COOKIE[str_replace('.', '_', $NameVersion)]);
if (!$Cookie) {
countdownload("unqiue_downloads.txt");
countdownload("unique_total_downloads.txt");
} else {
countdownload("downloads.txt");
countdownload("total_download.txt");
}
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$DownloadName.'" />';
?>
Naturally though, the user accesses the pre-download page first, so its not created yet. I do not want to add any functions to the pre download page, i want it to be plain and simple and not alot of adding/changing.
Edit:
Something like this would work, but its not working for me?
$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
Download #: <?php
$hits = '';
$filename = "downloads.txt";
if (file_exists($filename)) {
$hits = file_get_contents($filename);
} else {
file_put_contents($filename, '');
}
echo $hits;
?>
you can also use fopen() with 'w+' mode:
Download #: <?php
$hits = 0;
$filename = "downloads.txt";
$h = fopen($filename,'w+');
if (file_exists($filename)) {
$hits = intval(fread($h, filesize($filename)));
}
fclose($h);
echo $hits;
?>
Type juggling like this can lead to crazy, unforeseen problems later. to turn a string to an integer, you can just add the integer 0 to any string.
For example:
$f = file_get_contents('file.php');
$f = $f + 0;
echo is_int($f); //will return 1 for true
however, i second the use of a database instead of a text file for this. there's a few ways to go about it. one way is to insert a unique string into a table called 'download_count' every time someone downloads the file. the query is as easy as "insert into download_count $randomValue" - make sure the index is unique. then, just count the number of rows in this table when you need the count. the number of rows is the download count. and you have a real integer instead of a string pretending to be an integer. or make a field in your 'download file' table that has a download count integer. each file should be in a database with an id anyway. when someone downloads the file, pull that number from the database in your download function, put it into a variable, increment, update table and show it on the client however you want. use PHP with jQuery Ajax to update it asynchronously to make it cool.
i would still use php and jquery.load(file.php) if you insist on using a text file. that way, you can use your text file for storing any kind of data and just load the specific part of the text file using context selectors. the file.php accepts the $_GET request, loads the right portion of the file and reads the number stored in the file. it then increments the number stored in the file, updates the file and sends data back to the client to be displayed any way you want. for example, you can have a div in your text file with an id set to 'downloadcount' and a div with an id for any other data you want to store in this file. when you load file.php, you just send div#download_count along with the filename and it will only load the value stored in that div. this is a killer way to use php and jquery for cool and easy Ajax/data driven apps. not to turn this into a jquery thread, but this is as simple as it gets.
You can use more concise equivalent yours function countdownload:
function countdownload($filename) {
if (file_exists($filename)) {
file_put_contents($filename, 0);
} else {
file_put_contents($filename, file_get_contents($filename) + 1);
}
}

Categories