boa服务器中如何使用cgi管理cookie(c语言)

mac2022-06-30  57

1

【方法1】

(1) 设置cookie

printf( "Set-Cookie:username=%s; path=/; \r\n ",username); printf("Content-type: text/html\n\n");

注意:设置cookie的语句要放在Content-type前,否则不能生效。

(2) 查看cookie

printf("Content-type: text/html\n\n"); printf("<html>\n"); info=getenv("HTTP_COOKIE"); if(info!=NULL) { sscanf(info,"username=%s",username); }

注意:HTTP_COOKIE而不是HTTP-COOKIE,很多网络资料上都写错了,结果查到的cookie数据为空。

 【参考网址】

http://www.purplepixie.org/cgi/howto.php

【方法2】

(1) 设置cookie

printf("<head>\n"); printf("<script charset=\"gb2312\" language=\"JavaScript\" >\n"); printf("function setCookie(c_name,value,expiredays) \ \n{ \ \nvar exdate=new Date(); \ \nexdate.setDate(exdate.getDate()+expiredays) \ \ndocument.cookie=c_name+ \"=\" +escape(value)+ \ \n((expiredays==null) ? \"\" : \"; expires=\"+exdate.toGMTString()); \ }\n"); printf("</script>\n"); printf("</head>\n");

在<body>标签中调用:

printf("<script type=\"text/javascript\">\n"); printf("setCookie('username','%s',1);\n",username); //printf("window.location.href=\"xxxx\";\n"); printf("</script>\n");

(2) 获取cookie

printf("<head>\n"); printf("<script charset=\"gb2312\" language=\"JavaScript\" >\n"); printf("function getCookie(c_name) \ \n{ \ \n if(document.cookie.length>0) \ \n { \ \n c_start=document.cookie.indexOf(c_name + \"=\"); \ \n if(c_start!=-1) \ \n { \ \n c_start=c_start + c_name.length+1; \ \n c_end=document.cookie.indexOf(\";\",c_start); \ \n if(c_end==-1) c_end=document.cookie.length; \ \n return unescape(document.cookie.substring(c_start,c_end)); \ \n } \ \n} \ \n return \"\"; \ \n}\n"); printf("</script>\n"); printf("</head>\n");

在<body>标签中调用:

printf("<script type=\"text/javascript\">\n"); printf("var temp;\n"); printf("temp=getCookie('username');\n"); printf("alert(temp);\n"); printf("</script>\n");

评注:查询cookie【方法2】,暂时没有找到合适的方法将得到的cookie值转化为字符串,只能用于js脚本中。可以结合【方法2】的设置cookie和【方法1】的查询cookie使用。

 

【参考网址】

http://www.w3school.com.cn/js/js_cookies.asp

2 如何关闭浏览器页面的同时清除cookie?

printf("<body οnunlοad=\"document.cookie=''\">\n");

 

 

 

 

转载于:https://www.cnblogs.com/J2EEPLUS/archive/2011/09/30/2487997.html

最新回复(0)