简体   繁体   中英

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:

HTML:

<html>
  <body>
    <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'>
    </form>
  </body>
</html>

CGI:

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

int main(void)
{

char *data;
char *token;
printf("Content-type:text/html\r\n\r\n");
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++;
              }
          token++;
          token = strtok(NULL, "&");
          }
    printf("The average is %s\n", token);
  }
  printf("</body></html>");
  exit(EXIT_SUCCESS);
}

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!

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);
    }
    else
    {
        printf("Malformed query string\r\n");
    }

    name = strtok(NULL, "&");
}

You can see it in "action" here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM