How To: Write Web Applications In C++

You can easily convert Win32 console applications to web server CGIs. The cout object sends to the client browser! But the content type needs to be specified. Here's a sample:

cout << "Content-Type: text/html\n\n";
cout << "<html>\n";
cout << " <head>\n";
  ...
cout << " </body>\n";
cout << "</html>\n";

Here are some other content types:
text/plainTXT files
application/vnd.ms-exceltab-delimited CSV files
vnd.wap.wmlWML wireless web pages
more...

Rename the EXE to CGI, and place it in the /cgi-bin (or /scripts) folder on a web server.


To read input from forms or from the query string (that follows the "?" after the URL), follow this example:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
  // to process a GET
  string s = getenv("QUERY_STRING");
  ...

  // to process a POST
  int contentLength = 0;
  char postString[1024] = {0};
  string s = "";

  if (getenv("CONTENT_LENGTH"))
    contentLength = atoi(getenv("CONTENT_LENGTH"));
  if (contentLength)
    cin.read(postString, contentLength);
  s = postString;
  ...
  return 0;
}

See: details about getenv


An example:
#include <cstdlib>  // OPTIONAL: for getenv
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char* buf = "Hello, World";

  // this is what makes it work:
  cout << "Content-Type: text/html\n\n";

  // just some content...
  cout << "<html><head><title></title></head>"
    << "<body>\n";
  cout << "The string length of\n\"" << buf 
    << "\"\nis " << strlen(buf) 
    << " characters.\n";
  cout << "<p>\n";

  // OPTIONAL
  // if there is a query string  
  //  (appended to the URL by a "?")...
  char* queryString = getenv("QUERY_STRING");
  if (queryString)
    cout << "The Query String is: <pre>"  
      << queryString << "</pre>\n\n";

  // OPTIONAL
  // read the complete client request
  //  (including cookies, environment vars,...)
  int contentLength = 0; 
  char postString[1024] = {0}; 
  if (getenv("CONTENT_LENGTH")) 
    contentLength = atoi(getenv("CONTENT_LENGTH")); 
  if (contentLength)
    cin.read(postString, contentLength); 
  cout << "<pre>" << postString << "</pre>";

  // ...and the closing tags
  cout << "</body></html>\n";
  cout.flush(); // do not forget this!
  return 0;
}