Query environment variables on FastCGI using C

0
4455
FastCGI
FastCGI

Usually, web servers provide some useful information via hidden environment variables. For example, some variables might sound familiar to you, SERVER_ADDR, REMOTE_ADDR, HTTP_USER_AGENT, HTTP_HOST, QUERY_STRING …

Check this link to see more variables.

To get value of those environment variables, use getenv() defined in stdlib.h

I wrote this code to demonstrate how it works,


/* file: get_env.c */
#include "fcgi_stdio.h"
// declare a list of environment variables
const char *ENV_VARS[] = {
    "DOCUMENT_ROOT",
    "HTTP_COOKIE",
    "HTTP_HOST",
    "HTTP_REFERER",
    "HTTP_USER_AGENT",
    "HTTPS",
    "PATH",
    "QUERY_STRING",
    "REMOTE_ADDR",
    "REMOTE_HOST",
    "REMOTE_PORT",
    "REMOTE_USER",
    "REQUEST_METHOD",
    "REQUEST_URI",
    "SCRIPT_FILENAME",
    "SCRIPT_NAME",
    "SERVER_ADMIN",
    "SERVER_NAME",
    "SERVER_PORT",
    "SERVER_SOFTWARE"
};
/**
 * print out all values of correspondent env variables
 */
void printEnvVars ()
{
    const char *format = "<p>%s : <strong>%s</strong></p>";
    int c = 0;
    for(; c < 20; ++c) {
        char *s = getenv(ENV_VARS[c]);
        if(s != NULL) {
            printf(format, ENV_VARS[c], getenv(ENV_VARS[c]));
        } else {
	    // no value
            printf(format, ENV_VARS[c], "(No value)");
        }
    }
}
/* entry point */
int main ()
{
    while(FCGI_Accept() >= 0) {
        /* response format */
        printf("Content-type: text/html"
               "\r\n\r\n");
        /* init html structure */
        printf("<!doctype html>"
               "<html lang=\"en\">");
        printf("<body>");
        /* show all env vars */
        printEnvVars();
        /* close tags */
        printf("</body>");
        printf("</html>");
    }
    return 0;
}

To build the code,


$ gcc -Wall get_env.c -lfcgi -o get_env.fcgi

and execute just like any other FastCGI application.