-2

This is most likely a PHP noobie question.

To test some server caching configuration, I added the following code to my test suite:

<?php

if (array_key_exists('visited', $GLOBALS))
{
   print_r("We have already met");
} else {
   print_r("Hello ShimmerCat");
}

$GLOBALS['visited']=1;
?>

I'm expecting this code to take differents path of the branch during a first and second request, but it is returning the second message always. How can I achieve what I want?

dsign
  • 12,340
  • 6
  • 59
  • 82
  • 4
    The expectation is wrong. `$GLOBALS` is not maintained between requests. – marekful Dec 19 '16 at 18:59
  • Thanks @marekful. Is there an easy way to main some state between requests? – dsign Dec 19 '16 at 18:59
  • 1
    When executed as an Apache module, PHP's global scope lives throughout the request and not shared with others. You can use `$_SESSION` to to maintain data within a session. – marekful Dec 19 '16 at 19:01

1 Answers1

4

PHP itself is stateless, meaning every time a user visits a PHP page, the whole operation is done from scratch with each variable being defined as in the script.

If you want to store data between views, the basic way is with cookies. If you want the details of what's remembered to be secure, use session cookies.

  • Thanks. This is for a test suite where the client is curl (so it won't obey cookies), and PHP is hosted by HHVM. Would $_SESSION work here? – dsign Dec 19 '16 at 19:04
  • $_SESSION still uses a cookie in the user's browser. the reason it's more secure is because it just stores an ID on the user's browser, with all the actual data stored on the server, accessible by the unique ID. I've never heard of [cookies not being accessible with CURL](https://ec.haxx.se/http-cookies.html) though.. – Hussein Duvigneau Dec 19 '16 at 19:08
  • Thanks for the links @Hussein, I had mistakenly assumed that using cookies with curl would require manual parsing of `Set-Cookie` headers and a `-HCookie:...` option later, but your link clarifies the situation. – dsign Dec 19 '16 at 19:20