Created
February 3, 2021 01:31
-
-
Save hedenface/1d4c3e9f4b7c892db7668619f070ea54 to your computer and use it in GitHub Desktop.
Basic C-based CGI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
1. compile with: `gcc -Wall -o demo.cgi demo.c` | |
2. ensure your cgi is enabled (`sudo a2enmod cgi` if using apache) | |
3. copy demo to your cgi-bin (possibly /usr/lib/cgi-bin/) (check your | |
server configuration) | |
4. load page (http://localhost/cgi-bin/demo.cgi?key1=val1&key2=val2) | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
char * page_title = "Basic Demonstration!"; | |
int main(int argc, char const *argv[]) | |
{ | |
char * request_method = NULL; | |
char * query_string = NULL; | |
/* this is the very minimum required header */ | |
printf("%s\r\n\r\n", "Content-type: text/html; charset=utf-8"); | |
printf("%s\n", "<!DOCTYPE HTML>"); | |
printf("%s\n", "<html>"); | |
printf("<head><title>%s</title></head>\n", page_title); | |
printf("%s\n", "<body>"); | |
/* | |
there are quite a few environment variables accessible, but | |
we are only accessing a few. please read rfc 3875: | |
https://www.ietf.org/rfc/rfc3875 | |
*/ | |
request_method = getenv("REQUEST_METHOD"); | |
query_string = getenv("QUERY_STRING"); | |
printf("<h1>Request method: %s</h1>\n", request_method); | |
if (query_string != NULL) { | |
char * key = NULL; | |
char * value = NULL; | |
char * token = NULL; | |
printf("<h3>Query string: %s</h3>\n", query_string); | |
token = strtok(query_string, "="); | |
printf("%s\n", "<table>"); | |
while (token != NULL) { | |
printf("<tr><td>%s</td>", token); | |
token = strtok(NULL, "&"); | |
printf("<td>%s</td></tr>\n", token); | |
token = strtok(NULL, "="); | |
} | |
printf("%s\n", "</table>"); | |
} | |
printf("%s\n", "</body>"); | |
printf("%s\n", "</html>"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment