구글와이드(336x280)_상단 2개


Cookies Make the Web Go 'Round IT 영문자료

Cookies Make the Web Go 'Round
by Adam DuVander 29 Jun 2006
Page 1

Here at Webmonkey, we get to tackle all the latest breakthroughs in web development technology. We play around with the newest bits of code and we tell you about them. Sometimes, the newest stuff isn't really so new. Take cookies, for example, the little bits of information that websites store on your computer. We've been writing about them for over a decade.
Cookies let you perform basic identity-based tasks on the web, like logging in to your email account or online banking system. Cookies are essential for maintaining identities during online sessions. You want to make sure that transfer goes to the right off-shore account, after all.
Back in the 1990s, Mark wrote an introduction to cookies and Len talked about what cookies can do for you. Really, cookies haven't changed that much since then. What has happened is that they are used a lot more... by almost every site out there.
Any site that requires a username and password needs a way to remember who you are. Your browser helps websites know who you are after you have logged in. Can you imagine having to enter your password on every page? No fun.
Privacy concerns have kept some users from accepting cookies. Sometimes, problems arise from complex rules to accept cookies from this site, but not that site, or only in certain situations. If your site requires a cookie and the cookie isn't accepted by the browser, the user needs to know. Otherwise, you might leave them logging in repeatedly and never getting anywhere. When that happens, users usually bolt. And you don't want them to leave, because then who's going to fill up your bank account with money and enable you make those transfers to your off-shore accounts?
The best thing to do is check whether the user is accepting cookies right before you actually need them, like on a login page. This way, you can give a nice, human error message that might even explain how to enable cookies.
Sometimes this pre-check is called "cookie sniffing," but I think that sounds dirty. But for lack of a better term, that's what I'll call it. On the following pages, I'll show how to check for whether cookies are enabled in a few popular programming languages: JavaScript, PHP, and ASP.NET.
Page 2 — JavaScript cookie sniffer

There's good news for JavaScripters: Webmonkey has ready-made JavaScript cookie access code that will make this pretty easy. JavaScript works in every modern browser (assuming the user hasn't disabled it, but that's another story) and you don't need a special server to use it.
Once you download the Webmonkey code, I recommend putting it into its own file. I called mine WM_cookies.js. Then, include it in the beginning of your HTML code, like so:
<html>
<head>
<script src="WM_cookies.js"></script>
</head>
<body>
...


Next, simply check for cookies using this code:
<script>
if (!WM_acceptsCookies)
{
document.write("<div style=\"width: 30%; margin: 0 35% 0 35%; padding: 15px; border: 1px solid black; background-color: #ccc; color: #000;\">Unfortunately, it looks like your browser doesn't accept cookies. Our site requires them to be able to remember you while you're signed in. <a href=\"http://www.betterbrowsing.com/how-to/?enable_cookies/\">How to enable cookies</a>.</div>");
}
</script>
Put this anywhere after the body tag. If the visitor isn't able to use cookies (for whatever reason), they will receive a nice message and a link to more information. Right now, that goes to a community site I setup to have non-tech-oriented information, but you might want to point to your own explanatory verbage.
Lastly, include the rest of your page. This will be seen by all visitors, whether or not they have cookies enabled:
<h1>The title of my page</h1>
<p>
Hello and welcome to this page, blah blah...
</p>
</body>
</html>


You can see the whole thing in action here. My same site mentioned above also shows how to disable cookies. This will help you test your cookie sniffing solutions.
Page 3 — PHP cookie sniffer

As I discussed in the introduction, it is important to find out whether a user can use cookies before starting anything that requires their use. Since cookies are used to remember stuff from one page to another, we can't have page two thinking that page one did something it didn't — and couldn't — do.
Setting a cookie in PHP is very easy:
setcookie("check", "ok"); 
This PHP function is used to create a new cookie. This one we named "check" and "ok" is its value.
Testing a cookie in PHP is also easy:
if ($_COOKIE["check"] == "ok")
{
  // stuff to do if we find the cookie
}

Here we just make sure that the cookie we created above is really there. PHP uses the $_COOKIE variable to access cookies. The cookie name (we called it "check") goes within the brackets. Then we are checking its value against our expected value ("ok").
But there's a catch! In order to set a cookie, we need to make a round-trip to the server. PHP reads in the headers (where the cookies live) as soon as the page is loaded. Since we created the cookie after the page was loaded, we can't know whether it takes until the next time a page is loaded. Egads!
Here's the game plan. The first time we load the page, we'll try to set a cookie. Easy enough. Then, we'll forward the user to the same page, only with a little something extra at the end of the URL (called the "query string"). That way we'll know it's the second time the user has been to the page.
When we see that extra stuff in the query string, we try to read in the cookie. If the cookie is there, success. If not, we have to give the user a nice message and a link to more information.
Here's the code to include at the very top of any PHP page that will need to use cookies:
<?
$cookie_error = "";
if ($_COOKIE["check"] != "ok") // only continue if we see no cookie
{
if ($_GET["docheck"] == "yes") // if this is the round-trip--we already set cookie, but we can't read it
{
$cookie_error = "<div style=\"width: 30%; margin: 0 35% 0 35%; padding: 15px; border: 1px solid black; background-color: #ccc; color: #000;\">Unfortunately, it looks like your browser doesn't accept cookies. Our site requires them to be able to remember you while you're signed in. <a href=\"http://www.betterbrowsing.com/how-to/?enable_cookies/\">How to enable cookies</a>.</div>";
}
else // this is the first page. Let's set a cookie and send the user to the second page
{
setcookie("check", "ok"); // try to set a cookie
$checkcode = "&docheck=yes"; // add query string item to show we've tried to set a cookie
if ($_SERVER["QUERY_STRING"] == "")
{
$checkcode = "?$checkcode";
}
header("Location: " . $_SERVER["REQUEST_URI"] . $checkcode);
}
}
?>
Then, you can start the real HTML page:
<html>
<body>
<?=$cookie_error?>

Immediately after the body tag comes the cookie error. If there was no error, it will be blank and not show up at all.
And lastly, the rest of your page:
<h1>The title of my page</h1>
<p>
Hello and welcome to this page, blah blah...
</p>
</body>
</html>

Now let's move on to sniffing cookies in ASP.NET
Page 4 — ASP.NET cookie sniffer

Setting a cookie in ASP.NET is pretty simple. Within the Page_Load section (or any other server code), use these lines:
Dim c As New System.Web.HttpCookie("check", "ok")
Response.Cookies.Add(c)
The first line creates a new cookie named "check" and sets "ok" as its value. Then, we add it to the the collection of cookies that ASP.NET tracks.
Testing a cookie in ASP.NET is as easy as this If statement:
If (Not Request.Cookies("check") is Nothing) Then
' stuff to do if we find the cookie
End If
Here, we just make sure that the cookie we created above is really there. ASP.NET uses the Request.Cookies collection to access cookies. The cookie name (we called it "check") goes within the parentheses. We are checking that it is Not Nothing. Double negatives are perfectly OK in ASP.NET.
Just like in PHP, there's a catch to this cookie business! In order to set a cookie, we need to make a round-trip to the server. ASP.NET reads in the headers (where the cookies live) as soon as the page is loaded. Since we created the cookie after the page was loaded, we can't know whether it takes until the next time a page is loaded.
Our game plan here is the same as before. The first time we load the page, we'll try to set a cookie. Then, we'll forward the user to the same page, only with a little something extra at the end of the URL (called the "query string"). That way we'll know it's the second time the user has been to the page.
When we see that extra stuff in the query string, we try to read in the cookie. If the cookie is there, success. If not, we have to give the user a nice message and a link to more information.
Here's the code to include at the top of an ASP.NET page that will need to use cookies:
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If (Request.Cookies("check") is Nothing) Then
If (Request.QueryString("docheck") = "yes") Then
litCookieError.Text = "<div style=""width: 30%; margin: 0 35% 0 35%; padding: 15px; border: 1px solid black; background-color: #ccc; color: #000;"">Unfortunately, it looks like your browser doesn't accept cookies. Our site requires them to be able to remember you while you're signed in. <a href=""http://www.betterbrowsing.com/how-to/?enable_cookies/"">How to enable cookies</a>.</div>"
Else
Dim c As New System.Web.HttpCookie("check", "ok")
Response.Cookies.Add(c)
Dim sCheckCode As String = "?" &
Request.QueryString.toString()?& "&docheck=yes"
Response.Redirect(Request.ServerVariables("SCRIPT_NAME") & sCheckCode)
End If
End If
End Sub
</script>
Then, you can start the real HTML page:
<html>
<body>
<asp:Literal id="litCookieError" runat="server"></asp:Literal>

Immediately after the body tag comes the spot for the cookie error. I'm using a Literal tag, which the Page_Load code fills in with the error. If there was no error, it will be blank and not show up at all.
And lastly, the rest of your page:
<h1>The title of my page</h1>
<p>
Hello and welcome to this page, blah blah...
</p>
</body>
</html>

And that's that. A little cookie sniffing, plus a humane error message, makes a less frustrated user. Even better, you're helping everyone by explaining the importance of cookies, all the while moving more dough into that off-shore account.

Did you love this article? Did you hate it? Think you can do better? Send us your Feedback. Feedback submitted here will be considered for publication on Webmonkey or Wired News, so if you don't want us to print your comments, please say so in your email.

null



바보들의 영문법 카페(클릭!!)

오늘의 메모....

시사평론-정론직필 다음 카페
http://cafe.daum.net/sisa-1

바보들의 영문법 다음 카페
http://cafe.daum.net/babo-edu/

티스토리 내 블로그
http://earthly.tistory.com/

내 블로그에 있는 모든 글들과 자료에 대한 펌과 링크는 무제한 허용됩니다.
(단, 내 블로그에 덧글쓰기가 차단된 자들에게는 펌, 트랙백, 핑백 등이 일체 허용되지 않음.)

그리고 내 블로그 최근글 목록을 제목별로 보시려면....
바로 아래에 있는 이전글 목록의 최근달을 클릭하시면 됩니다.
그러면 제목을 보고 편하게 글을 골라 보실 수 있습니다.

그리고 내 블로그내 글을 검색하시려면 아래 검색버튼을 이용하시면 됩니다.


가가챗창

flag_Visitors

free counters