代码:
//##############################常用功能模块类##############################
class GlobalFunc
{
public:
FILE *cgiIn,*cgiOut;
int firstCookie;
void GlobalFuncInit();
void CookieSetInteger(char *name, int value, int secondsToLive,
char *path, char *domain);
void CookieSetString(char *name, char *value, int secondsToLive,
char *path, char *domain);
char *GetCookieVal(char *cookieName);
void HeaderLocation(char *redirectUrl);
};
//类初始化函数
void GlobalFunc::GlobalFuncInit()
{
this->firstCookie=1;
this->cgiOut=stdout;
}
//设置int型cookie值
void GlobalFunc::CookieSetInteger(char *name, int value, int secondsToLive,
char *path, char *domain)
{
char svalue[256];
sprintf(svalue, "%d", value);
this->CookieSetString(name, svalue, secondsToLive, path, domain);
}
//设置string型cookie值
void GlobalFunc::CookieSetString(char *name, char *value, int secondsToLive,
char *path, char *domain)
{
fprintf(this->cgiOut,
"Set-Cookie: %s=%s; Domain=%s; Max-Age=%d; Path=%s; \r\n",
name, value, domain, secondsToLive, path);
}
//重定向url地址
void GlobalFunc::HeaderLocation(char *redirectUrl)
{
if (!this->firstCookie)
{
fprintf(cgiOut, "\r\n");
}
fprintf(cgiOut, "Location: %s\r\n\r\n", redirectUrl);
}
//获得cookie值
char *GlobalFunc::GetCookieVal(char *cookieName)
{
char *cookieVal,*cookies,*name,*value;
cookieVal=NULL;
if(!(cookies=getenv("HTTP_COOKIE")))
{
return NULL;
}
for(name=strtok(cookies,";");name;name=strtok(NULL,";"))
{
while(isspace((unsigned char)*name))
{
name++;
}
value=strchr(name,'=')+1;
*(value-1)='\0';
if(!strcmp(name,cookieName))
{
if(!(cookieVal=strdup(value)))
{
return NULL;
}
break;
}
free(cookies);
}
return cookieVal;
}