c/c++ 对cookie的操作
Posted 邱洋inCloud
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c/c++ 对cookie的操作相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
char *getcookie(char *var)
{
char *p= getenv("HTTP_COOKIE");
char sstr[1024]= {0};
char *str;
char *q;
char *retstr;
char ch;
if(p)
{
strcpy(sstr, var);
strcat(sstr, "=");
str=strstr(p, sstr);
if(str)
{
str += strlen(var)+1;
q= str;
while(*q!='/0' && *q!= ';') q++;
if(q== str) return NULL;
retstr= malloc(q-str+1);
strncpy(retstr, str, q-str);
retstr[q-str]= '/0';
return retstr;
}
}
return NULL;
}
void setcookie(char *var, char *value)
{
char str[1024];
strcpy(str, var);
strcat(str, "=");
strcat(str, value);
strcat(str, ";");
printf("set-cookie: %s/n", str);
}
char *getvalue(char *name)
{
char *p, *q;
char *chp;
char sstr[1024]= {0};
char *ret;
int len;
p= getenv("CONTENT_LENGTH");
if(p) len= atoi(p);
else len= 0;
chp= malloc(len+1);
fread(chp, len, 1, stdin);
chp[len]= '/0';
strcpy(sstr, name);
strcat(sstr, "=");
p= strstr(chp, sstr);
if(p)
{
p += strlen(name)+1;
q= p;
while(*q!='/0' && *q!= '&') q++;
if(q== p) return NULL;
ret= malloc(q-p+1);
strncpy(ret, p, q-p);
ret[q-p]= '/0';
return ret;
}
return NULL;
}
int main()
{
char *p;
char *vp;
int len;
if(strcmp(getenv("REQUEST_METHOD"), "POST")== 0)
{
vp= getvalue("value");
}else
{
vp= NULL;
}
p= getcookie("name");
if(vp)
{
setcookie("name", vp);
}
printf("Content-Type: text/html/r/n/r/n");
printf("<html><head>");
/*if(vp)
{
printf("<META http-equiv=/"refresh/" content=/"5;/cgi-bin/cookie/">");
}*/
printf("<title>test cookie</title></head>");
printf("<body>");
if(p) printf("cookie: %s<br>", p);
if(vp)
{
printf("write cookie: name=%s", vp);
printf("<br><a href=/"/cgi-bin/cookie/">next</a>");
}else if(!p)
{
printf("<form action=/"/cgi-bin/cookie/" method=/"post/">");
printf("name=<input type=/"text/" name=/"value/">");
printf("<input type=/"submit/">");
}
printf("</body></html>");
}
以上是关于c/c++ 对cookie的操作的主要内容,如果未能解决你的问题,请参考以下文章