user3520573
user3520573

Reputation: 117

increment variable each time page gets called or opened?

<!doctype html>
<html>
<head>
<title>Index</title>
</head>
<form action="newquestion.php" method="post">
Question <input type="text" name="question">
<input type="submit">
</form>
<body>
</body>
</html>

PHP file...

<?php

static $q = 1;

echo $q;

$q++;

?>

I'm new in PHP. Will this not increment $q by 1 each time "newquestion.php" is called? if not how to increment this variable each time this page(newquestion.php) gets called or opened?

Upvotes: 0

Views: 7745

Answers (7)

The easy way is using a SESSION or a COOKIE based persistence methodology.

Using SESSION example:

In the beggining of the page (firt line prefered) put the following code:

session_start();

Check if a session for this user has been created and recorded, if so, increment by one the value of q session variable and display it.

If not, initialize q session variable with value 1, store and display.

 if(!isset($_SESSION["q"]) //check if the array index "q" exists
   $_SESSION["q"] = 1; //index "q" dosen't exists, so create it with inital value (in this case: 1)
 else 
   $_SESSION["q"]++; //index "q" exists, so increment in one its value.

 $q = $_SESSION["q"]; //here you have the final value of "q" already incremented or with default value 1.
 //doSomethingWith($q);

Using COOKIE example:

$q = 0; //Initialize variable q with value 0
if(isset($_COOKIE["q"])) //check if the cookie "q" exists
   $q = $_COOKIE["q"]; //if so, override the q value 0 with the value in the cookie
$q++; //increment in one the q value.
setcookie("q",$q); //send a HTTP response header to the browser saving the cookie with new value

//doSomethingWith($q);
//here you have the final value of "q" already incremented or with value 1 like in session.

With cookies, you cannot use $_COOKIE["index"] = value for set a value for cookie, you must use setcookie instead for that. $_COOKIE["index"] is only for read the cookie value (if it exists).

SESSION still use cookie, but only for identify that user is the owner of that session, the user cannot change the value of session directly (only if you provide a way to they do that).

Using COOKIE the user will see a cookie with name "q" and it's value and can easily change the value through simple javascript code, browser tools (like Google Chrome Developer Console Tool) or any extension for Browser (Edit This Cookie, a Google Chrome extension that list all cookies, values and parameters for a webpage).

Remeber that any session_start call (only one per page is necessary) or setcookie calls must be made before any buffer output like (but not just) echo, print. Because both calls produces a HTTP Header "Set-Cookie" and HTTP Headers must be sent before content body, calling this methods after a buffer flushing will throw a exception.

The two examples above are per user count. If you need a per application or per page count, you must implement a custom counter system, using file system to store data (the pageviews/page requests) or database to track individuals request (with date, ip address, page url, page name, anything else).

Upvotes: 2

sss999
sss999

Reputation: 528

The problem with your code is that the variable is first set to 1 each and everytime the page is visited. You will have to make use of $_SESSION. But then again the problem with using session variable would be that if you are trying to increase the value of your variable from different PCs or different systems, session would not work. For this the best thing will be to insert the value in database.

Upvotes: 0

foxygen
foxygen

Reputation: 1388

No, because $q resets to 1 each time the page is called. You need some sort of persistence strategy (database, writing to a text file, etc) in order to keep track of the page views.

It's also a good idea to consolidate this functionality into a class, which can be used across your code base. For example:

class VisiterCounter {

    public static function incrementPageVisits($page){

        /*! 
         * Beyond the scope of this question, but would
         * probably involve updating a DB table or
         * writing to a text file
         */
        echo "incrementing count for ", $page;
    }

}

And then in newquestion.php,

VisiterCounter::incrementPageVisits('newquestion.php');

Or, if you had a front controller that handled all of the requests in your web application:

VisiterCounter::incrementPageVisits($_SERVER['REQUEST_URI']);

Upvotes: 5

Carsten Hellweg
Carsten Hellweg

Reputation: 214

or put the variable to increment in the session. with that, you could at least see, how often one user calls your pages.

Upvotes: 0

Awlad Liton
Awlad Liton

Reputation: 9351

Every php script inside in a page is executed when you are loading this page. So everytime your script is executes line by line. You can not count page loading number by the process you are trying.

you can follow one of the process below:

1) you can save it to the database and each time when it is loading you can execute query to increment the count value.
2) you can do it by session like this:

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

Upvotes: 4

Bik
Bik

Reputation: 553

Put $q initialization in any of your init page then increment the value.

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33522

It won't work as you think. PHP code is executed each time from start to finish - meaning that no variables are kept over from one run to the next.

To get around this, you could use a session variable (this is a special sort of variable) which will keep a value in it that you could keep for each visitor to the site. This will however work for EACH VISITOR individually.

If you want to increment the value for all users (you open the first one, it says 1, I open the second it says 2 and so on) you will need to either store it in a database (good option), write it out to a text file (not really a good option) or magic up some other way to keep it saved.

Upvotes: 0

Related Questions