Tracking Unregistered Users in Yii / PHP

I am trying to track the activities of all unregistered users on my site. The goal is to save this activity so that I can add it to my profile when he creates an account.

I am using the below behavior to assign a cookie to new users and use that cookie as the basis for the "temp user" row in my Users table. This way the user can immediately start interacting with my API.

This seems to work fine. However, I can see that more "temporary users" are being created in my database than I have site visitors - around 2,500 compared to around 500 visits yesterday (according to Google Analytics).

Is there something wrong with the behavior below, or am I doing something else wrong? Is there a better way?

  <?php
class ApplicationBehavior extends CBehavior
{
    private $_owner;

    public function events()
    {

        return array(
            'onBeginRequest' => 'setCookies'

        );
    }

    public function setCookies()
    {

        $owner = $this->getOwner();

        if ($owner->user->getIsGuest() && !isset(Yii::app()->request->cookies['dc_tempusername'])):
            $tempusername = genRandomString(20);
            $tempuser           = new User();
            $tempuser->username = $tempusername;
            $tempuser->email    = "noemailyet@tempuser.com";
            if (isset(Yii::app()->request->cookies['dc_tempusername'])) {
                $tempuser->name = Yii::app()->request->cookies['dc_tempusername']->value;
            } else {
                $tempuser->name = "CookieBasedTempuser";
            }
            $tempuser->points  = 1;
            $tempuser->firstip = $_SERVER['REMOTE_ADDR'];
            if ($tempuser->validate()) {
                Yii::app()->request->cookies['dc_tempusername'] = new CHttpCookie('dc_tempusername', $tempusername);
                $cookie                                         = new CHttpCookie('dc_tempusername', $tempusername);
                $cookie->expire                                 = time() + 60 * 60 * 24 * 180;
                Yii::app()->request->cookies['dc_tempusername'] = $cookie;
                $tempuser->save();
            } else {
                echo CHtml::errorSummary($tempuser);
            }
        endif;

    }
}
?>

      

+3


source to share


1 answer


Check if cookies are allowed:
Check if cookies are enabled

If we are correct, every time you see that the user is a guest and does not have a cookie, you create a new user temp.

Why not check if the cookie is set first, if so then create a temporary user? You will need to set 2 cookies: an initial temp cookie for validation and then your cookie 'dc_tempusername'

.



You can even go as far as using Browscap to check against known bots:
https://github.com/browscap/browscap-php
http://browscap.org/

You will need to specify the browser in php.ini

+1


source







All Articles