来自 HTML 的 CGI- 密码不会打印

CGI- Password from HTML won't print

我们被要求使用 C、HTML、MySQL 和 CGI​​ 创建一个类似 Twitter 的程序。第一步是创建登录页面,我们会要求用户输入他们的用户名和密码。我在这样做时使用了 CGI x HTML,这是我的程序:

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);
}

问题:输入用户名和密码并按下提交按钮后,cgi 不打印任何内容。它只是空白 space。我该如何解决这个问题并能够打印用户在用户名和密码框中输入的内容?谢谢!

对于初学者,我建议您复制getenv 获得的字符串。您永远不应该修改从 getenv 获得的字符串,而 strtok 会修改它。

此外,当您调用 strtok 时,您获得的指针指向 name=value 对中名称的开头。通过修改指针变量(你用 token++ 做的)你失去了开始并且不再有指向名称的指针。

那我建议你看看像strchr这样的东西来简化代码并且没有内循环。

把它们放在一起,如果可能的话,你可以做类似的事情

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 = '[=10=]';
        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, "&");
}

你可以see it in "action" here.