gpt4 book ai didi

html - 获取以某种格式编码的 url 参数值

转载 作者:行者123 更新时间:2023-11-30 18:56:14 30 4
gpt4 key购买 nike

我编写了下面的 C 代码来获取 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

�l12�

请纠正我哪里做错了?谢谢

最佳答案

这是我使用 strstr 创建的一个快速函数strchrmemchr 。这就是您正在寻找的。

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

char *find_param(char *param, char *query_str) {
char *p, *p2, *value;

p = strchr(query_str, '?');
if (!p)
return NULL;

do {
p = strstr(p+1, param);
} while (p && p[strlen(param)] != '=');

if (!p)
return NULL;

p += (1 + strlen(param));

p2 = memchr (p, '&', strlen(p));
if (!p2)
p2 = p + strlen(p);

value = malloc(p2 - p + 1);
strcpy(value, p);
value[p2 - p] = '\0';

return value;
}

int main() {
printf("%s", find_param("u", "http://example.com/cgi-bin/cgi_param?u=1212&sa=232%203&sdd=jdwjdjw"));
return 0;
}

打印:

1212

也适用于 sasdd .

关于html - 获取以某种格式编码的 url 参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24979843/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com