用C语言实现PHP的urlencode函数

标签: , , ,

题目好像弄错了,PHP本身就是用C语言写,所以准确来说题目应该是PHP的urlencode函数的C语言源码。在用C语言写某个程序(至于是什么程序,参见其他文章)的时候要用到PHP的urlencode函数。好在PHP是开源的,就搜索了一下PHP的源码,在php-5.3.2\ext\standard\url.c文件中找到了PHP的urlencode函数的C语言源代码,感兴趣的可以下载PHP源码看看。但是因为用到了PHP源码中的其他函数,urlencode的源代码不能直接用到C语言程序中,我参考源码修改了一下,就可以直接使用了。代码如下,s为需要urlencode的字符串,len为字符串的长度,new_length为urlencode后新字符串的长度:

char *php_url_encode(char const *s, int len, int *new_length)
{
	#define safe_emalloc(nmemb, size, offset)	malloc((nmemb) * (size) + (offset))
	static unsigned char hexchars[] = "0123456789ABCDEF";
	register unsigned char c;
	unsigned char *to, *start;
	unsigned char const *from, *end;
	
	from = (unsigned char *)s;
	end = (unsigned char *)s + len;
	start = to = (unsigned char *) safe_emalloc(3, len, 1);

	while (from < end) {
		c = *from++;

		if (c == ' ') {
			*to++ = '+';
#ifndef CHARSET_EBCDIC
		} else if ((c < '0' && c != '-' && c != '.') ||
				   (c < 'A' && c > '9') ||
				   (c > 'Z' && c < 'a' && c != '_') ||
				   (c > 'z')) {
			to[0] = '%';
			to[1] = hexchars[c >> 4];
			to[2] = hexchars[c & 15];
			to += 3;
#else /*CHARSET_EBCDIC*/
		} else if (!isalnum(c) && strchr("_-.", c) == NULL) {
			/* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */
			to[0] = '%';
			to[1] = hexchars[os_toascii[c] >> 4];
			to[2] = hexchars[os_toascii[c] & 15];
			to += 3;
#endif /*CHARSET_EBCDIC*/
		} else {
			*to++ = c;
		}
	}
	*to = 0;
	if (new_length) {
		*new_length = to - start;
	}
	return (char *) start;
}

不想复制粘贴的可以直接下载源码

[download id=10]

随机文章:

  1. 微软的VBScript教程
  2. 在Windows下编译zlib 1.25
  3. getElementsByName的用法
  4. VBS和UAC用户帐户控制
  5. JavaScript 记忆(Memoization)

4 条评论 发表在“用C语言实现PHP的urlencode函数”上

  1. luochong说道:

    项目中需要用到这个函数,博主研究php的源代码,不错不错!

  2. 夜色迷离说道:

    正在研究中,谢谢分享了

  3. shuo说道:

    多谢楼主

  4. I was recommended this web site by way off my cousin. I’m noot sure whether this publish is written by means
    of him as noo one else recognise such special about
    my difficulty. You are amazing! Thanks!

留下回复