I have written a server in fcgi and C and I need to add some custome parameter after I printed some String to request.out. to be clear this is my sample code:
while (1)
{
rc = FCGX_Accept_r(&request);
if (rc < 0)
break;
FCGX_FPrintF(request.out,
"Content-type: text/html\r\n"
"\r\n");
//the html page content
FCGX_FPrintF(request.out,
"<form method=\"post\" action=\"\">"
"<input type=\"text\" name=\"num\">"
"<input type=\"submit\" value=\"click\" name=\"submit\">"
"</form>"
);
.
.
.
//and somewhere like here I need to add a cookie parameter
FCGX_FPrintF(request.out,
"set-cookie:myParam=myValue\r\n"
"\r\n");
.
.
.
.
FCGX_Finish_r(&request);
}
But this ends up printing right to the page. How can I put it to the start of the buffer?
The HTTP protocol has the following schema for requests and responses:
<header 1>\r\n
<header 2>\r\n
...
<header n>\r\n
\r\n
<body>
So any header that you need to send must be sent before the empty line that separates the headers and body section of the response.
In your case, you need to write the set-cookie
header either before, or immediately after Content-Type
, otherwise the browser will interpret it as part of the response body. Also, I'd recommend following the casing convention:
FCGX_FPrintF(request.out,
"Content-type: text/html\r\n"
"Set-Cookie: myParam=myValue\r\n"
"\r\n");