0

I am using the PHP-CPP library to develop PHP extensions.

When I try the following in C++:

#include <phpcpp.h>

static int number=0;

Php::Value get_num()
{
    number++;
    return number;
}

And the following in PHP:

<?php
    echo get_num();
?>

Everything works as expected for awhile, but then the "number" variable randomly resets back to zero. Also, pressing CTRL+F5 in Firefox, the "number" variable again resets back to zero.

How do I avoid "number" from resetting?

LogicalException
  • 566
  • 2
  • 7
  • 16
  • 3
    global !== persistent... if you need persistence between requests, then you need to store the value outside of PHP (e.g. session, filesystem, database, redis, memcached, whatever) – Mark Baker Jun 27 '14 at 15:22
  • 1
    The value is already stored outside of PHP. It is stored in the C++ shared library (PHP Extension). – LogicalException Jun 27 '14 at 15:29
  • So you're saying that PHP is capable of persistence across all requests from any source if a value is stored in a shared library? All this every request is a separate thread nonsense that PHP developers preach is a nonsense? I wish I'd known that years ago – Mark Baker Jun 27 '14 at 16:25
  • Well my sample code is working as expected, I keep refreshing the page and the number keeps counting upwards... That's prove values are persistent across different requests (until PHP decides to reset these values). – LogicalException Jun 27 '14 at 17:29
  • Well if your code is written in C++, then surely PHP isn't resetting anything – Mark Baker Jun 27 '14 at 19:16
  • Hence my original question... What's going wrong? – LogicalException Jun 27 '14 at 19:32

2 Answers2

5

A global C++ variable in a PHP extension is not persistent.

It all depends on the setup of your webserver. If you use Apache for example (and most others have a similar setup), there are multiple instances of the webserver process running, all serving pageviews. Each of these instances has its own global 'number' variable. That's why you do not see the number incrementing as you had expected: not every pageview is served by the same Apache instance.

On top of that: when the load of your webserver goes up or goes down, new Apache processes are started and stopped, and new 'number' variables are created with an initial value of 0. Also, an Apache process normally restarts after a certain fixed number of pageviews (set in the apache configuration file), which also sets the counter back to zero.

In your own small testing environment, you do not run into this problem that fast, because the load is so low that it can all be handled by a single instance of the webserver, but on a live busy server you will certainly encounter this.

If you want to use a persistent counter, you will have to store it somewhere else, for example in a file or database.

-1

you should use Mutex for disable share access from multi thread

Mohsen Davari
  • 11
  • 1
  • 7