Magento: Track Visitor’s (User / Customer) Information

Here, I will show you how to track visitor’s data information in Magento. By visitor’s information, I mean information like remote address, http host, user agent (browser), referer url, first visit date time, last visit date time, etc.

The following code fetches the vistor data:-

[source language=”php”]
$visitorData = Mage::getSingleton(‘core/session’)->getVisitorData();

// printing visitor information data
echo "<pre>"; print_r($visitorData); echo "</pre>";
[/source]

You will get an array of visitor information data like the following one:-

[source language=”php”]
Array
(
[] =>
[server_addr] => 167772437
[remote_addr] => 167772437
[http_secure] =>
[http_host] => 127.0.0.1
[http_user_agent] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10
[http_accept_language] => en-US,en;q=0.8
[http_accept_charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
[request_uri] => /magento/index.php/catalog/category/view/id/22
[session_id] => 13qm5u80238vb15lupqcac97r5
[http_referer] => http://127.0.0.1/magento/
[first_visit_at] => 2011-01-17 11:42:23
[is_new_visitor] =>
[last_visit_at] => 2011-01-17 11:58:38
[visitor_id] => 41
[last_url_id] => 139
)
[/source]

In the above array, the server_addr and remote_addr are in different form than usual. The (IPv4) Internet Protocol dotted address has been converted into a proper address using ip2long PHP function. You can get the same kind of value from the following code:-

[source language=”php”]
// user’s ip address (visitor’s ip address)
$remoteAddr = Mage::helper(‘core/http’)->getRemoteAddr(true);

// server’s ip address (where the current script is)
$serverAddr = Mage::helper(‘core/http’)->getServerAddr(true);
[/source]

Hope this helps. Thanks.