从 cgi POST 数据中获取输入

Smi*_*yne 1 c++ post cgi input scanf

这是我用 cgi 检索 html 数据的 c++ 代码。

char* fileContentLength;
int nContentLength;
fileContentLength = getenv("CONTENT_LENGTH");

if(fileContentLength == NULL)   
    return -1;      

nContentLength = atoi(fileContentLength);   

if(nContentLength == 0) 
    return -1;

data = (char*) malloc(nContentLength+1);

if(data == NULL)    
    return -1;

memset(data, 0, nContentLength+1);  
if(fread(data, 1, nContentLength, stdin) == 0)  
    return -1;

if(ferror(stdin))
Run Code Online (Sandbox Code Playgroud)

执行此代码后,我得到了变量“data”的以下结果。

f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=

这里 f0,l0,f1,l1 是 HTML 页面输入框的名称。从这个字符串中,我需要将 fname0、lname0、fname1、lname1 等值分开。我使用了 sscanf 功能。但我无法检索到正确的结果。如何将上述字符串中的值分配给名为 firstname 和 lastname 的局部变量。

Som*_*ude 5

检查例如strtok功能。使用它在循环中拆分以将'&'所有键值对转换为向量(例如)。然后通过向量strtok'='字符处拆分每个字符串(您可以在此处再次使用)。您可以将键和值放在 a 中std::map,也可以直接使用。

对于更多特定于 C++ 的方法,请使用 egstd::string::findstd::string::substr而不是strtok。然后,您可以将键和值直接放入映射中,而不是将它们临时存储为向量中的字符串。

编辑:如何获得最后一对

最后一个键值对不是由'&'字符终止的,因此您必须在循环检查最后一对。这可以通过复制您的字符串来完成,然后在最后一个'&'. 可能是这样的:

char *copy = strdup(data);

// Loop getting key-value pairs using `strtok`
// ...

// Find the last '&' in the string
char *last_amp_pos = strrchr(copy, '&');
if (last_amp_pos != NULL && last_amp_pos < (copy + strlen(copy)))
{
    last_amp_pos++;  // Increase to point to first character after the ampersand

    // `last_amp_pos` now points to the last key-value pair
}

// Must be free'd since we allocated a copy above
free(copy);
Run Code Online (Sandbox Code Playgroud)

之所以需要使用字符串的副本,是因为strtok修改了字符串。

我仍然建议您使用 C++ 字符串,而不是依赖旧的 C 函数。它可能会简化一切,包括您不需要为最后一个键值对添加额外的检查。