Introduction
Few days ago, I had a problem in my CGI application where I must capture the data inside the HTTP POST request coming to the application. The post data are XML data that I must parse and process. In this tip/trick, I will share the idea and the solution I found.
Background
There are few things at least you must know, types of HTTP requests and the HTTP request format, so I suggest you check this detailed article on Wikipedia on the HTTP protocol. I also suggest you review some CGI concepts especially the environment variables.
Using the Code
The idea behind the solution is the CGI environment variables, especially the CONTENT_LENGTH
variable. This variable indicates the number of bytes (size) of the data passed within a POST HTTP request.
Any C/C++ application has standard input and output, so when you run the application as CGI, the standard input/output will be through server. So to read the post data, you read the value of CONTENT_LENGTH
and then read from stdin
. Here is how it is done:
char* len_ = getenv("CONTENT_LENGTH");
if(len_)
{
long int len = strtol(len_, NULL, 10);
cout << "LENGTH = " << len << endl;
char* postdata = (char*)malloc(len + 1);
if (!postdata) { exit(EXIT_FAILURE); }
fgets(postdata, len + 1, stdin);
cout << "DATA = " << postdata << endl;
free(postdata);
}
else
{
}
Points of Interest
Always check for the value of CONTENT_LENGTH
, if no data is available within the request, it becomes null
. And always allocate extra location for the null
terminator.