我寫下面的C代碼來獲取url參數的值。得到的URL參數值以某種格式編碼
char *param(char *attribute_name) {
char *query_str = getenv("QUERY_STRING");
urlDecode(query_str);
printf("qstr = %s<br/>", query_str);
int i;
char *param_value;
char *temp = malloc(strlen(attribute_name) + 3);
char *x;
strcpy(temp, "?");
strcat(temp, attribute_name);
strcat(temp, "=");
x = strstr(query_str, temp);
attribute_name = strdup(attribute_name);
if (x == NULL) {
free(temp);
temp = malloc(strlen(attribute_name) + 3);
strcpy(temp, "&");
strcat(temp, attribute_name);
strcat(temp, "=");
x = strstr(query_str, temp);
}
if (x != NULL) {
param_value = malloc(strlen(x) - strlen(temp) + 1);
int s = strlen(x) - strlen(temp);
int t = strlen(x) - s;
strncpy(param_value, &x[t], 1);
for (i = strlen(temp) + 1; i <= strlen(x); i++) {
if (x[i] != '&') {
strncat(param_value, &x[i], 1);
} else {
break;
}
}
}
free(temp);
return param_value;
}
int urlDecode(char *str) {
unsigned int i;
char tmp[BUFSIZ];
char *ptr = tmp;
memset(tmp, 0, sizeof(tmp));
for (i=0; i < strlen(str); i++) {
if (str[i] != '%') {
*ptr++ = str[i];
continue;
}
if (!isdigit(str[i+1]) || !isdigit(str[i+2])) {
*ptr++ = str[i];
continue;
}
*ptr++ = ((str[i+1] - '0') << 4) | (str[i+2] - '0');
i += 2;
}
*ptr = '\0';
strcpy(str, tmp);
return 0;
}
而下面是我的main()函數:
int main() {
printf("Content-type: text/html\n\r\n\r");
printf("<!Doctype html>");
printf("<html>");
printf("<meta charset=\"UTF-8\"><meta http-equiv=\"Content-type\" content=\"text/html; charset=UTF-8\">");
printf("<body>");
char attr[] = "u";
char *value = param(attr);
puts(value);
//free(value);
printf("</body></html>");
return 0;
}
而下面是我打的網址後,瀏覽器的接收到的輸出:http://example.com/cgi-bin/cgi_param?u=1212&sa=232%203&sdd=jdwjdjw
QSTR = U = 1212 & SA = 232 3 & sdd = jdwjdjw
請指正我在哪裏做錯了? 謝謝
首先縮小錯誤點,並指定這是C還是C++(看起來像C) –
三件事:首先是['strncpy'](http://en.cppreference.com/w/c/string/字節/ strncpy)可能並不總是添加字符串終止符,在你的情況下它不會。其次,爲什麼使用例如'strncpy'只是爲了複製*一個*字符?第三,使用調試器一行一行地瀏覽代碼,看看會發生什麼。 –
您是否已經調試過您的代碼?我們不是人類調試器(但是...但我們仍在努力提高我們的運行時技能) – NirMH