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数据为空。
【方法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_startc_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>标签中调用: