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:
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
I just couldn’t depart your site prior to suggesting that I extremely enjoyed the standard information an individual provide for your visitors? Is gonna be back frequently in order to inspect new postsanchor text
Hello, you used to write fantastic, but the last several posts have been kinda boring… I miss your tremendous writings. Past several posts are just a bit out of track! come on!
I truly appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thanks again
Wow! Thank you! I always wanted to write on my website something like that. Can I include a part of your post to my site?
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.
Hi there! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
Whoa! This blog looks just like my old one! It’s on a totally different topic but it has pretty much the same page layout and design. Great choice of colors!
Hmm it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any tips for novice blog writers? I’d definitely appreciate it.
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!
Once I originally commented I clicked the -Notify me when new feedback are added- checkbox and now every time a remark is added I get 4 emails with the identical comment. Is there any method you may take away me from that service? Thanks!
Lovely site! I am loving it!! Will come back again. I am taking your feeds also.
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!
You completed a number of nice points there. I did a search on the issue and found nearly all people will have the same opinion with your blog.betflik
I am extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it’s rare to see a nice blog like this one these days..
I’ve learn several excellent stuff here. Certainly worth bookmarking for revisiting. I wonder how so much attempt you set to create this kind of fantastic informative site.
Pretty component to content. I simply stumbled upon your blog and in accession capital to claim that I acquire actually loved account your blog posts. Any way I’ll be subscribing in your augment and even I fulfillment you access persistently quickly.
This is very fascinating, You are an excessively professional blogger. I have joined your rss feed and look ahead to in search of more of your fantastic post. Additionally, I have shared your website in my social networks!
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..
I used to be suggested this website through my cousin. I am not sure whether or not this submit is written through him as no one else know such unique about my trouble. You are wonderful! Thank you!
Thank you for the auspicious writeup. It if truth be told was a enjoyment account it. Look complicated to more added agreeable from you! However, how can we communicate?
Do you have a spam problem on this site; I also am a blogger, and I was curious about your situation; many of us have created some nice procedures and we are looking to exchange strategies with other folks, why not shoot me an email if interested.
You made some clear points there. I looked on the internet for the topic and found most persons will agree with your blog.
I don’t even understand how I ended up right here, however I thought this put up used to be great. I do not know who you might be but definitely you’re going to a well-known blogger in case you are not already 😉 Cheers!
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!
You completed a number of nice points there. I did a search on the issue and found nearly all people will have the same opinion with your blog.betflik
I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back in the future. Cheers