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.
Related
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);
?>
Something seems wrong with my php script, but I have no idea what it is. The only possible thing that seems to be wrong is something to do with the cache, but I am not sure. Here's my script, I'll tell you what's happened below the code:
<?php
set_time_limit(0);
header('Content-Type:text/event-stream');
$prevmod=$lastmod=filemtime('chattext.txt');
function waitformod(){
global $lastmod;
global $prevmod;
while($prevmod==$lastmod){
usleep(100000);
clearstatcache();
$lastmod=filemtime('chattext.txt');
}
echo 'data:'.file_get_contents('chattext.txt').PHP_EOL.PHP_EOL;
flush();
$prevmod=$lastmod;
}
while(true){
waitformod();
}
?>
This is supposed to be used with the JavaScript EventSource and send the contents of chattext.txt whenever it is modified. The file does not output anything, however. I think it is because of the infinite loop. Is there any way to fix this?
Does something like this work better?
<?php
set_time_limit(0);
header('Content-Type:text/event-stream');
$prevmod = $lastmod = filemtime('chattext.txt');
function waitformod(){
global $lastmod;
global $prevmod;
while($prevmod == $lastmod) {
usleep(100000);
clearstatcache();
$lastmod = filemtime('chattext.txt');
}
echo 'data:'.file_get_contents('chattext.txt').PHP_EOL.PHP_EOL;
flush();
$prevmod = $lastmod;
}
while(1) {
waitformod();
}
Your current code looks like it reads the file, outputs it, waits for it to change, and then terminates.
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);
?>
Is there any way to check if an included document via include('to_include.php') has returned anything?
This is how it looks:
//to_include.php
echo function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
include('to_include.php');
if($the_return_of_the_include != '') {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
So after I've included to_include.php in my main document I would like to check if anything was generated by the included document.
I know the obvious solution would be to just use function_that_generates_some_html_sometimes_but_not_all_the_times() in the main_document.php, but that's not possible in my current setup.
make function_that_generates_some_html_sometimes_but_not_all_the_times() return something when it outputs something and set a variable:
//to_include.php
$ok=function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
$ok='';
include('to_include.php');
if($ok != '') {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
If you are talking about generated output you can use:
ob_start();
include "MY_FILEEEZZZ.php";
function_that_generates_html_in_include();
$string = ob_get_contents();
ob_clean();
if(!empty($string)) { // Or any other check
echo $some_crap_that_makes_my_life_difficult;
}
Might have to tweak the ob_ calls... I think that's right from memory, but memory is that of a goldfish.
You could also just set the contents of variable like $GLOBALS['done'] = true; in the include file when it generates something and check for that in your main code.
Given the wording of the question, it sounds as if you want this:
//to_include.php
return function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
$the_return_of_the_include = include 'to_include.php';
if (empty($the_return_of_the_include)) {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
} else {
echo $the_return_of_the_include;
}
Which should work in your situation. That way you don't have to worry about output buffering, variable creep, etc.
I'm not sure if I'm missing the point of the question but ....
function_exists();
Will return true if the function is defined.
include()
returns true if the file is inclued.
so wrap either or both in an if() and you're good to go, unless I got wrong end of the stick
if(include('file.php') && function_exists(my_function))
{
// wee
}
try
// to_include.php
$returnvalue = function_that_generates_some_html_sometimes_but_not_all_the_times();
echo $returnvalue;
//main_document.php
include('to_include.php');
if ( $returnvalue != '' ){
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
$file = ".$dirN/$filename.";
$count_my_page = (".$dirname1/$filename.$extens");
if(fopen(".$file.","r"))
{
$hits = file($count_my_page);
$nHits = ((int) $hits[0]) + 1;
$fp = fopen($count_my_page , "w");
fputs($fp , $nHits . "");
fclose($fp);
echo $nHits;
}
I want the count to increase only when i read the file, but it happens other wise on refreshing the page where the link of the file is present.
Clicking a link and refreshing a page are only differt actions on the client, there's no difference to the server; it just sees a HTTP request.
I don't think this can be done without using JavaScript to set some kind of form variable when the link is clicked.
iam not sure if i understand the question but you can try the following :
Add an parameter to the link used to read the file like :
http://www.localhost.de/readfile.php?read=true
in your count method check for the parameter:
if ($_request['read'] === true) {
// count
-> do an redirect to remove the parameter, or set it to false ..
} else {
// nothing
}