Chitika

Thursday, November 3, 2011

C++: CGI POST Data

Following is the code to process HTTP-Post request, it stores the result in map<string, string>, idea is taken from http://www.openroad.org/cgihelp/cgi.html. To decode code from HTTP encoding to is taken from http://www.cs.tut.fi/~jkorpela/forms/cgic.html.


void ProcessPostQueryString(map<string,string>& query) {


        //FILE *fp = fopen("post.txt", "w+");
        char tmp[5*1024];

        char *ptmp = getenv("CONTENT_LENGTH");

        if(ptmp == NULL || strlen(ptmp) < 1) {
                return;
        }


        int contentLength = atoi(getenv("CONTENT_LENGTH"));
        char queryStr[5*1024];

        //sprintf(tmp, "content length[%d]\n", contentLength);
        //fputs(tmp, fp);
        //fflush(fp);

        if(contentLength > sizeof(queryStr)) {

                throw "only 5K of Post query string supported";
        }

        //fputs("post data: ", fp);
        int length=contentLength;
        //while(length > 0)
        {
                int nread = fread(queryStr, length, 1, stdin);
                //fputs(queryStr, fp);

                length -= nread;
        }
        queryStr[contentLength] = 0;

        //fputs("\n", fp);
        //fflush(fp);

        char *ptrSentence=NULL,
                 *ptrWord=NULL;
        char *savPtr1, *savPtr2;
        ptrSentence=strtok_r(queryStr, "&", &savPtr1);
        while (ptrSentence != NULL) {


                //cout << '[' << ptrSentence << ']' << endl;
                ptrWord = strtok_r(ptrSentence, "=", &savPtr2);
                if(ptrWord == NULL && strlen(ptrWord) < 1)  continue;
                string key(ptrWord);
                ptrWord = strtok_r(NULL, "=", &savPtr2);
                if(ptrWord !=NULL && strlen(ptrWord) > 0) {

                        int len=strlen(ptrWord);
                        HTMLDecode(ptrWord, ptrWord+len, tmp);
                        tmp[len]=0;

                        string value(tmp);
                        query[key]=value;

                        sprintf(tmp, "(%s)=(%s)\n", key.c_str(), value.c_str());
                        //fputs(tmp, fp);
                        //fflush(fp);
                }

                ptrSentence=strtok_r(NULL, "&", &savPtr1);
                if(ptrSentence==NULL)  break;

        }

        //fclose(fp);
}

Following is the code to decode HTML encoded string:

int HTMLDecode(char *src, char *last, char *dest)
{
    int sz=0;
 for(; src != last; src++, dest++, sz++)
   if(*src == '+')
     *dest = ' ';
   else if(*src == '%') {
     int code;
     sscanf(src+1, "%2x", &code) != 1;
     *dest = code;
     src +=2; }
   else
     *dest = *src;

 *dest=0;
 return sz;
}

No comments:

Post a Comment