Kyle Ramos Kyle Ramos - 1 year ago 64
C Question

CGI- Password from HTML won't print

We were asked to create a twitter-like program using C, HTML, MySQL and CGI. The first step is creating the login page wherein we would ask the user to enter their username and password. I used CGI x HTML in doing that and here are my programs:


<form action='/cgi-bin/password .cgi'>
Username: <input type="text" name="user" ><br>
Password: <input type="password" name ="password" id="password" maxlength="10">
<input type ="submit" value='Submit'>


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)

char *data;
char *token;
printf("<!DOCTYPE html><html><head><title>Is Your Password and username this?<title></head><body>");
data = getenv("QUERY_STRING");
if (data) {
token = strtok(data, "&");
while (token) {
while (*token != '=')
token = strtok(NULL, "&");
printf("The average is %s\n", token);

PROBLEM: After entering the username and password and pressing the submit button, the cgi is not printing anything. It's just blank space. How do I fix this and be able to print what the user enetered in the username and password boxes? Thanks!

Answer Source

For starters I suggest you copy the string you get from getenv. You should never modify the string you get from getenv, and strtok modifies it.

Also, when you call strtok the pointer you get is pointing to the beginning of the name in the name=value pair. By modifying the pointer variable (which you do with token++) you lose the start and will not have a pointer to the name anymore.

Then I suggest you look at something like strchr to simplify the code and don't have the inner loop.

Putting it all together, if it is possible you could do something like

char *data_ptr = getenv("QUERY_STRING");
char data[strlen(data_ptr) + 1];  // +1 for the string terminator
strcpy(data, data_ptr);

char *name = strtok(data, "&");
while (name != NULL)
    char *value_sep = strchr(name, '=');
    if (value_sep != NULL)
        *value_sep = '\0';
        char *value = ++value_sep;

        printf("Name = %s\r\n", name);
        printf("Value = %s\r\n", value);
        printf("Malformed query string\r\n");

    name = strtok(NULL, "&");

You can see it in "action" here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download