1

I have the following PHP code which counts every access to the page. If I call the side direct it counts certain. If I make a Ajax call it starts always again with 1.

<?php
session_start();    
header('Access-Control-Allow-Origin: *');

        if (!isset($_SESSION['zaehler'])) {
          $_SESSION['zaehler'] = 1;
        } else {
          $_SESSION['zaehler']++;
        }
echo  $_SESSION['zaehler'];


?>

I understand that an ajax call is the same like an direct call by reading this: Do AJAX requests retain PHP Session info? How can I count each ajaxCall as long as the side is open?

I'm doing a simple jquery ajaxCall:

    $.get( "http://www.huntinggrounds.de/aa.php", function( data ) {
         console.log( "dataResponse: ", data );
    }) .fail(function(jqXHR, textStatus ) {
        console.log( "error",textStatus);
       })
       .always(function() {
        console.log( "finished" );
       });

I made test-files, testfile.html, just a black screen. Click on desktop and see the counter in your console the php-file is here.

Community
  • 1
  • 1
hamburger
  • 1,078
  • 4
  • 16
  • 37

3 Answers3

5

After testing your pages, your problem is related to your domain.

http://www.huntinggrounds.de/aa.html is working fine, not http://huntinggrounds.de/aa.html

For security reasons, cookie is per-domain specific. Cookie set by PHP on http://huntinggrounds.de/aa.html will not work on http://www.huntinggrounds.de/aa.html depending of your configuration.

To by pass this problem, don't set full URL in your ajax. Preferer relative URI.

$.get( "/collect?"+setParameter(defs),
 function( data ) {
      try {
             console.log("New count is : ",data);
          } catch(e) {
             // if there is no response
             console.log( "No answer : ", data);
         }
  }) 
Kevin Labécot
  • 1,947
  • 12
  • 25
  • you are right it seems to work. But on future use I'am calling the file from different pages. I will store how often the user did his ajax-call in a database. So that mean I cant do that serverside? – hamburger Aug 18 '14 at 12:15
  • You can allow subdomains to share the session's cookie by updating the default PHP configuration. Try to put this at the top of your PHP page (before session_start) : `ini_set('session.cookie_domain', '.huntinggrounds.de' );` – Kevin Labécot Aug 18 '14 at 12:17
  • Try to put this directive directly into php.ini, maybe ini_set is not allowed to you. – Kevin Labécot Aug 18 '14 at 12:25
  • Try this too : `session_set_cookie_params(0, '/', '.huntinggrounds.de');` – Kevin Labécot Aug 18 '14 at 12:27
  • do not run my own server, so I have no access to php.ini. Can I check it somewere – hamburger Aug 18 '14 at 12:28
  • session_set_cookie_params(0, '/', '.huntinggrounds.de');: CHECKED do not work – hamburger Aug 18 '14 at 12:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/59503/discussion-between-hamburger-and-kevin-labecot). – hamburger Aug 18 '14 at 12:30
0

I see you put this in the comments.

you are right it seems to work. But on future use I'am calling the file from different pages. I will store how often the user did his ajax-call in a database. So that mean I cant do that serverside?

My question for your question is why even bother with the session, just store it in the database the whole time. The reason I post this as an answer is because what happens if they close the browser? before you save it in the database.

Granted you will still want to get the session working. Because on the server side you may want to pull their user id or other information out of it.

To explain the session issue: My money is on the domain path ( www. sub-domain -vs- no sub-domain ) that others have mentioned as to why you are having problems with the session cookies. It's not really that you are losing the session. But most likely, if you were to view the cookies stored in your browser for the site you will probably have 2 of them. Which means that you are using one session for the www. sub-domain and one for the site without the domain.

You can always force the www. on your site with some .htaccess rules too. .htaccess - how to force "www." in a generic way?

Anyway, the specifics below depend on your exact implementation, which is why I'm not posting code. On the server side.

  1. authenticate use in the session, Or you could do IP address here etc...

  2. Use user id for unique field in database, or user id and some other field(s) like date or url visited.

  3. have a numeric field 'views' or such. And, maybe a field for the url they are visiting?

  4. on each ajax request pull the users record out of the DB, increment the view field and save any other data you want too.

The database queries will be super fast just pulling out one row each with a good numeric index, like a user id etc..

In short I would just skip the whole saving in the session bit, because like I hinted at if they close the browser you lose your count. Besides, how will you know when to save it in the database? There is no way to tell sever side when they disconnect, except for to use a heartbeat like the ajax call. You cant rely on them to log out properly.

I have implemented a similar system, to track time spent doing data entry by some outside contractors we use at my Job.

In that implantation, I use the id of record they are editing, and their user ID as keys, then I have a timestamp for last viewed time, so that when the ajax call hits I pull out the last viewed time ( if its less then a few minutes old ) and in a separate field I keep the total seconds spent working. Then with some basic math I can add the new elapsed seconds into the total and wah-lah, I can keep a fairly accurate track of how long they have the record open for.

Community
  • 1
  • 1
ArtisticPhoenix
  • 20,683
  • 2
  • 18
  • 34
0

As seen in previous answers your problem is happening when trying to access one domain cookies from a second one that doesn't have them.

There is an underlaying problem on having both domains serve the page and that is content duplication penalty on search engines as the www and non www access count as two sites.

You can address both issues by using only one url as the canonical one and redirecting the other. This can be done via .htaccess or if you dont have that kind of server access in a config file (loaded at the beginning of every page) with the following code:

if ('www.' != substr($_SERVER['SERVER_NAME'], 0, 4)) {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: http://www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
    exit();
}
Martin Buezas
  • 364
  • 2
  • 8