我们被要求使用 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 不打印任何内容。这只是空白区域。如何解决此问题并能够打印用户在用户名和密码框中输入的内容?谢谢!
最佳答案
对于初学者,我建议您复制从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 = '\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, "&");
}
关于html - CGI - HTML 中的密码不会打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089370/