如何实现网站访问来源统计

  本例子自实现了统计域名来源,未统计域名后的查询字符串。如搜索引擎查询后找到你站点的记录,查询字符串不在统计范围内。
  流程就是先通过Request.ServerVariables("http_referer")【asp】或者Request.ServerVariables["http_referer"]/Request.UrlReferrer【asp.net】得到来源页面的url,然后写入数据库中。
  
  数据库tb中的统计表ref
+展开
-SQL
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ref]'and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[ref]
GO

CREATE TABLE [dbo].[ref] (
[Host] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[click] [intNOT NULL 
ON [PRIMARY]
GO


  然后是更新数据库的存储过程
+展开
-SQL
CREATE PROCEDURE updateref
@host nvarchar(200)
as
declare @num int
select @num=count(*) from ref where host=@host
if @num=0 --没有此条主机记录则插入
  insert into ref values(@host,1)
else--更新
 update ref set click=click+1 where host=@host
GO


  下面是c#的一个类,用来调用存储过程更新数据库表
+展开
-C#
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class DBOP
{
    /// <summary>
    /// 更新来源统计
    /// </summary>
    /// <param name="cn">数据库连接对象</param>
    public static void UpdateRef(SqlConnection cn)
    {
        //这里注意判断是有有来源页面
        string refHost = HttpContext.Current.Request.UrlReferrer == null ? "" : HttpContext.Current.Request.UrlReferrer.Host.ToLower();
        if (refHost != "" && refHost.IndexOf("/") == -1)//如果是你自己的域名不用统计
        {
            if (refHost.StartsWith("www.")) refHost = refHost.Substring(4);//去掉www.
            try
            {
                SqlCommand cm = new SqlCommand("updateref", cn);
                cm.CommandType = CommandType.StoredProcedure;//设置为存储过程
                cm.Parameters.Add(new SqlParameter("@host", SqlDbType.NVarChar, 200, refHost));//添加参数
                cm.ExecuteNonQuery();//执行
            }
            catch { }
        }
    }
}




asp就比较简单了,由于没有返回记录,所以使用连接对象的execute方法即可。
+展开
-VBScript
sub updateref
  dim cn,refUrl,sindex,eindex
  refUrl=Request.ServerVariables("http_referer")
  if refUrl<>"" then
    '正则获取主机部分
    set reg=new RegExp
    reg.pattern="https?://(www.)?([^/]+)"
    set ms=reg.execute(url)
    for each m in ms
      refurl=m.submatches(1):exit for
    next
    set reg=nothing
    if instr(refUrl,"/")=0 then'不统计自己的站点
       set cn=Server.CreateObject("ADOBD.Connection")
       cn.open "driver={sqlserver};server=.;uid=sa;pwd=;database=db"'注意更新你的驱动
       cn.execute "exec updateref '"&refUrl&"'"'==========
       cn.close:set cn=nothing
    end if
  end if
end sub

加支付宝好友偷能量挖...


原创文章,转载请注明出处:如何实现网站访问来源统计

评论(0)Web开发网
阅读(157)喜欢(0)Asp.Net/C#/WCF