译者吐槽:我觉得这个办法挺2的。
最近一个客户的项目需要进行一项跟踪:最近一段时间里,用户的注册过程中是否会看到一个升级注册的广告。如果用户点击了这个广告并且立即完成注册,那没什么好做的,用Google自定义跟踪代码就满足需求了。
如果使用Cookie来解决这个问题,会非常的简单。然而,我们的注册过程是在spacetowel.com,广告却运行在 luxurycement.com,因为跨域安全的问题,我们无法访问其他域名下的Cookie。(这一规则是用于防止其他站点获取不属于本站的Cookie信息)。
既然我们无法获取 luxurycement.com, 的Cookie信息,spacetowel.com需要在 luxurycement.com 上做一点手脚。跟踪像素一般是一个1x1的gif图片。因为客户浏览器向服务器提交了这个载入图片的请求,我们可以在这一时机加入cookie,用于后续的读取。有了这个Cookie,我们对注册过程中广告是否出现的检测和跟踪就很容易了。
在Drupal中提供一个跟踪像素功能非常简单。首先注册一个page callback:
/**
* Implements hook_menu().
*/
function dm_tracking_pixel_menu() {
$items = array();
$items['track.gif'] = array(
'page callback' => 'dm_tracking_pixel_gif',
'file' => 'dm_tracking_pixel.pages.inc',
'access arguments' => array('access tracking pixel'),
);
return $items;
}
上面的代码让 spacetowel.com/track.gif 返回一个图片,有趣的是这个callback的执行内容,这一方法来自于Stack Overflow。
<?php
/**
* Page callback for showing a simple tracking pixel.
*/
function dm_tracking_pixel_gif() {
ignore_user_abort(true);
// Ensure the tracking pixel is always served by Drupal so the cookie is set.
drupal_page_is_cacheable(FALSE);
// Store the last time they saw an ad.
$cookie_data = array();
// Set some data you want to store here, and then set the cookie.
user_cookie_save($cookie_data);
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', 1);
}
ini_set('zlib.output_compression', 0);
if (ob_get_level() == 0) {
ob_start();
}
drupal_add_http_header('Content-encoding', 'none');
drupal_add_http_header('Content-type', 'image/gif');
drupal_add_http_header('Content-Length', '42');
drupal_add_http_header('Cache-Control', 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate');
drupal_add_http_header('Expires', 'Wed, 11 Jan 2000 12:59:00 GMT');
drupal_add_http_header('Last-Modified', 'Wed, 11 Jan 2006 12:59:00 GMT');
drupal_add_http_header('Pragma', 'no-cache');
// 这就是图片,不需要GD
echo sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%',71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59);
ob_flush();
flush();
ob_end_flush();
drupal_exit();
}
最后要确认你的ad团队在广告中添加对这个跟踪像素的引用。
Drupal 版本