Como testar o tempo de sessão do meu site?

Os scripts abaixo tem como finalidade testar o tempo de vida de uma sessão, as informações são gravadas em um banco de dados access Os dados gravados no banco são ip , id da sessão , hora inicial e hora final

Criando o sessao.mdb

Primeiro deve ser criado um banco de dados access com nome de sessao.mdb, crie a tabela sessao conforme descrição abaixo:

Como testar o tempo de sessão do meu site?

Se quiser, pode usar o script:

 create table sessao (id_sessao text(50), hora_inicial text(50), hora_final text(50), ip text(50)) 

Crie agora o arquivo nova_sessao.asp com o código abaixo:

 <% set conexao=server.CreateObject("Adodb.Connection") conexao.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:/home/login/dados/sessao.mdb" %> <div align="center"> <p><font size="5" face="Verdana, Arial, sans-serif">Teste de Sessão</font></p> <p><font size="2" face="Verdana, Arial, sans-serif">[<a href="del_sessao.asp?valor=del"> <b>Zerar tudo</b></a> ]</font> [ <b><font size="2" face="Verdana, Arial, sans-serif"><a href="del_sessao.asp?valor=abandona">Abandonar a Sessão</a></font></b> ]</p> <% strsql = "select ip,id_sessao,hora_inicial,hora_final from sessao order by hora_inicial desc" set rs = conexao.execute(strsql) if rs.eof then sql7 = "insert into sessao (ip, id_sessao , hora_inicial ) values ('"& request.servervariables("Remote_Addr") &"','"& session.sessionid &"','"& now &"')" conexao.execute(sql7) %> <meta http-equiv="refresh" content="1"> <% response.end end if vsessao = rs("id_sessao") vhora_final = rs("hora_final") %> <table width="90%" border="0" bgcolor="#eaeaea"> <tr> <td width="20%"> <div align="center"><font size="2" face="Verdana, Arial, sans-serif"><b>IP</b></font></div> </td> <td width="24%"> <div align="center"><b><font size="2" face="Verdana, Arial, sans-serif">Sessão Atual:</font></b></div> </td> <td width="21%"> <div align="center"><b><font size="2" face="Verdana, Arial, sans-serif">Hora Inicio:</font></b></div> </td> <td width="15%"> <div align="center"><b><font size="2" face="Verdana, Arial, sans-serif">Hora Final:</font></b></div> </td> <td width="20%"> <div align="center"><b><font size="2" face="Verdana, Arial, sans-serif">Duração:</font></b></div> </td> </tr> <%while not rs.eof%> <tr bgcolor="#FFFFFF"> <td width="20%"> <div align="center"><font face="Verdana, Arial, sans-serif" size="2"><%=rs("ip")%></font></div> </td> <td width="24%"> <div align="center"><font size="2" face="Verdana, Arial, sans-serif"><%=rs("id_sessao")%></font></div> </td> <td width="21%"> <div align="center"><font size="2" face="Verdana, Arial, sans-serif"><%=rs("hora_inicial")%></font></div> </td> <td width="15%"> <div align="center"><font size="2" face="Verdana, Arial, sans-serif"><%=rs("hora_final")%></font></div> </td> <td width="20%"> <div align="center"><font size="2" face="Verdana, Arial, sans-serif"><%=DateDiff("n", rs("hora_inicial"), rs("hora_final"))%> minutos</font></div> </td> </tr> <% rs.movenext wend %> </table> <% '******************************** se o id_sessao do banco for igual ao sessionid , então nada é executado if vsessao = session.sessionid then response.end end if  if vsessao <> session.sessionid and vhora_final = "" then sql2 = "insert into sessao (id_sessao , hora_inicial ) values ('"& session.sessionid &"','"& now &"')" conexao.execute(sql2) response.end end if if vsessao <> session.sessionid then sql1 = "update sessao set hora_final = '"& now & "' where id_sessao ='"& vsessao &"'" conexao.execute(sql1) sql3 = "insert into sessao (ip, id_sessao , hora_inicial ) values ('"& request.servervariables("Remote_Addr") &"','"& session.sessionid &"','"& now &"')" conexao.execute(sql3) end if %> <p><font size="2" face="Verdana, Arial, sans-serif"><a href="nova_sessao.asp?valor=zerar"> </a></font></p> </div> <% rs.close set rs = nothing conexao.close set conexao = nothing %> 

Arquivo para zerar as informações do banco e matar a sessão

Crie o arquivo del_sessao.asp utilizando o código abaixo. Este arquivo será responsavel por zerar todas as informações do banco e também para matar a sessão.

 <% if request.querystring("valor") = "abandona" then session.abandon response.redirect "nova_sessao.asp" end if if request.querystring("valor") = "del" then  set conexao=server.CreateObject("Adodb.Connection") conexao.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:/home/login/dados/sessao.mdb"  del = "delete from sessao" conexao.execute(del) end if conexao.close set conexao = nothing response.redirect "nova_sessao.asp" %> 

Veja também


    Veja exemplos de conexão com o banco Access via script ASP.

    Windows 2008

    Use o exemplo abaixo para realizar uma conexão sem utilizar uma DSN.

    ConnString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:/home/LOGIN_DE_FTP/dados/bancoAccess.accdb;Persist Security Info=False;" Set Conexao = Server.CreateObject("ADODB.Connection") Conexao.Open ConnString Set Registros = Server.CreateObject("ADODB.Recordset") Registros.Open "Clientes", Conexao

    Note acima que Data Source=E:/home/LOGIN_DE_FTP/dados/bancoAccess.accdb; representa o caminho de seu site dentro do servidor, que está sob o diretório e:/home/LOGIN_DE_FTP .

    O diretório será: e:/home/LOGIN_DE_FTP/dados

    Windows 2012

    No ambiente Windows 2012 o driver utilizado é o mesmo, porém o caminho físico setado é diferente, neste caso o caminho a ser utilizado deve ter sempre o formato:

    //windows-pd-0001.fs.locaweb.com.br/WNFS-0001/Loginftp/CaminhodoBanco

    Veja um exemplo utilizando este caminho:

    <%  'Declarando variáveis Dim adoCon, strCon   'Conectando com o banco strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=//windows-pd-0001.fs.locaweb.com.br/WNFS-0001/Loginftp/Dados/NomedoBanco"   'Criando objeto Set adoCon = Server.CreateObject("ADODB.Connection")   'Abrindo conexão adoCon.Open strCon   '##Tratamento de erro. Caso ocorra problemas na conexão, exibe esta informação e apresenta detalhes. If Err.Number <> 0 Then     response.write "<b><font color='red'> Falha na conexão !</font></b>"     response.write "<BR><BR>"     response.write "<b>Erro.Description:</b> " & Err.Description & "<br>"     response.write "<b>Erro.Number:</b> " & Err.Number & "<br>"     response.write "<b>Erro.Source:</b> " & Err.Source & "<br>" Else    '##Caso a conexão seja bem sucedida, mostra mensagem de confirmação.    response.write "<b><font color='blue'> Conexão OK !</font>" End If   'Fechando conexão adoCon.Close   Set adoCon = Nothing %>

    Sempre deve-se colocar os bancos de dados access dentro da pasta dados, pois ela não está exposta na web, garantindo assim a segurança do conteúdo contra downloads diretos.

    Fechando a conexão

    Com o comando Registros.Open a conexão foi criada. Você pode fechá-la com os seguintes comandos:

     Registros.Close Set Registros = Nothing 

    Veja também


    O artigo ajudou ?
    SimNão

    28 Comments

    I am commenting to let you understand what a impressive discovery my wife’s girl gained visiting the blog. She came to understand too many issues, which include what it is like to possess a great helping character to get the mediocre ones without hassle know precisely various hard to do issues. You actually did more than her desires. Thanks for imparting such invaluable, safe, revealing and even easy tips on that topic to Mary.

    Wow, wonderful weblog layout! How long have you been blogging for? you make running a blog look easy. The entire glance of your site is wonderful, as smartly as the content material!

    I believe that is among the such a lot vital info for me. And i’m glad studying your article. However want to statement on few basic things, The site style is great, the articles is in reality great : D. Excellent job, cheers

    Hello very cool blog!! Man .. Excellent .. Wonderful .. I’ll bookmark your blog and take the feeds also…I am satisfied to seek out so many helpful information right here within the put up, we need work out extra techniques on this regard, thanks for sharing. . . . . .

    I think other site proprietors should take this website as an model, very clean and great user friendly style and design, let alone the content. You are an expert in this topic!

    hey there and thank you for your info – I’ve definitely picked up anything new from right here. I did however expertise several technical points using this website, as I experienced to reload the web site a lot of times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I’m complaining, but slow loading instances times will often affect your placement in google and could damage your high quality score if advertising and marketing with Adwords. Well I am adding this RSS to my email and could look out for a lot more of your respective interesting content. Make sure you update this again very soon..

    Hello there! I know this is kinda off topic nevertheless I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa? My blog addresses a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Great blog by the way!

    Deixe uma resposta