How to continue incrementing the value of a variable even after a page is reloaded?

Asked

Viewed 1,424 times

5

I wanted to add +1 in the variable $a every time the page is loaded.

I’ve used the code:

  $a = ++$a;
  echo $a

and also the:

  $a = $a++;
  echo $a

But it only adds once, and when I refresh the page, it doesn’t add anything else. Someone can give me a hint?

  • 1

    face ta totally disorganized your question, but I’ll give you a hint: use for: http://php.net/manual/en/control-structures.for.php

  • Try to be clearer on the question, specify better what you are looking for.

  • None of the answers were accepted, none of them helped you?

4 answers

9


$txt="";
$arquivo="";
$visitas="";

    $txt        = "contador.txt";
    $arquivo    = fopen($txt,"a+");
    $visitas    = fgets($arquivo,1024);
    fclose($arquivo);

    $arquivo    = fopen($txt,"r+");
    $visitas    = $visitas + 1;
    fwrite($arquivo,$visitas);
    fclose($arquivo);  


    echo "Esta página foi visitada $visitas vezes";

The function fopen opens the specified file in the variable $txt.

The way r+ opens for reading and writing; places the file pointer at the beginning of the file.

The function fgets returns a row of an open file with the specified length (optional - specifies the number of bytes to read). Default is 1024 bytes.

The function fwrite allows writing to files,

This answer answers the author’s comment in David Santos' reply.

Voce could give me an example of how to do this to save to a txt file - Henrique Romulo 9/07 at 2:44

  • I don’t know if the editing was due to my criticism, but actually I imagine that maybe the AP might not know what does the functions fopen and fclose... so I said that there was no explanation...

  • @Wallacemaxters was on account of the downvote, but his remark was good. I will edit and put some explanation

  • I was the one who was negative. But since you have proposed to explain, I will remove it. The idea was only to stimulate explain better. Some people may think it helps AP, but other users will come because of this problem and will be left with questions about what was done in the answer.

  • @Wallacemaxters For this reason I think that every negative vote should have a comment so that the author of the answer can adjust it as suggested in his comment!

  • sensational, dude. It was ball show edition. + 1

  • 1

    Thanks to your comment!!!!

Show 1 more comment

6

As was said by David Santos, when reloading the page the values are not saved. They are recorded there only at runtime, after that they are removed from memory.

In PHP, there are several ways to maintain values. A two most common for your case would be the use of Session or Cookies.

I would choose to use the session. Sessions maintain a bridge between client and server, allowing you to save specific values for each client (browser) that loads your page.

In your case, the variable $_SESSION (as quoted in one of the answers, but without any explanation as to what it would be).

Behold:

// inicia a sessão. Deve ser colocado antes de todo o código de saída para o 
//navegador e antes de usar a variável super global `$_SESSION

session_start();

// Se existir o índice 'a', incrementa. Se não, define 0  
if (isset($_SESSION['a'])) {

  $_SESSION['a']++;

} else {

  $_SESSION['a'] = 0;

}

// imprime o valor
var_dump($_SESSION['a']);

The above code will work as follows: $_SESSION will be stored on the server, with a unique identification for the client (browser, which is registered in a Cookie). No if we have the isset defining whether the index 'a' exists in the array of $_SESSION. If it exists, it increases the values. But if it does not exist, we define that it will be 0.

Thus, every time the page is reloaded, the value will also be modified and you will be saved in the session.

See More:

Here is an explanation about the fact that every Session uses Cookies

Sessions are used a lot to log in users:

User counter

In my humble opinion, if you want to do a user counter, as has been pointed out in some comments, I think the best way is to use a database.

6

The script stores the values of the variables only at runtime, after which the space in the memory occupied by them is released. Every time you refresh the page the script goes back to its original state.

If you want to save the value of a variable even after updating the page, you will need to save the value of it in a place external to the file, for example : xml, database, txt, among others...

  • 2

    or even cookies, and sessions.

  • Voce could give me an example of how to do this to save to a txt file

5

It’s easy, try using the code below:

<?php

if(isset($_SESSION['a'])) {
    $_SESSION['a'] += 1;
} else {
    session_start();

    $_SESSION['a'] = 1;
}

echo $_SESSION['a'];
  • Well I thought about it, I suggested the for for him, but after I saw that he wants to save values even updating the page. I think Cookies also serves.

  • 1

    True @Guilhermealves, cookies also solve the case, but it depends on the goal, if he wants the counter to work for different users, the way is to store even the counter somewhere.

  • @Fabianolothor vc could explain to me if possible how to store in a txt file and how to make it take that number that is in the txt file and add +1

  • @romulohenrique because you’re going the long way?

  • @Guilhermealves, has a way but easy as

  • @Guilhermealves, I’m wanting that when a person among him disappears but 1 equals those visitors contactor

  • @romulohenrique, has plugins for this. but if you want to do it, Fabiano has already given his hand. just try

  • I think it’s a big problem you teach how to do, but do not explain anything in your reply @Fabianolothor. You may have noticed that if the Questioner did not know that a variable would not be incremented because of the exception time, it is a sign that he needs a brief explanation about the use of sessions and the like.

  • This solves the AP problem, but it would be interesting to explain why it solves as well.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.