php_url_encode

最近几天在折腾网站的url规范化的问题。

对urlencode函数比较好奇,扒出C代码来看了一下。原来是16进制的东东。

Ascii Table : http://www.asciitable.com/

C代码 (取自php-5.2.6/ext/standard/url.c 430-489行)
  1. /* rfc1738: 
  2.  
  3.    …The characters ";", 
  4.    "/", "?", ":", "@", "=" and "&" are the characters which may be 
  5.    reserved for special meaning within a scheme… 
  6.  
  7.    …Thus, only alphanumerics, the special characters "$-_.+!*'(),", and 
  8.    reserved characters used for their reserved purposes may be used 
  9.    unencoded within a URL… 
  10.  
  11.    For added safety, we only leave -_. unencoded. 
  12.  */  
  13.   
  14. static unsigned char hexchars[] = "0123456789ABCDEF";  
  15.   
  16. /* {{{ php_url_encode 
  17.  */  
  18. PHPAPI char *php_url_encode(char const *s, int len, int *new_length)  
  19. {  
  20.     register unsigned char c;  
  21.     unsigned char *to, *start;  
  22.     unsigned char const *from, *end;  
  23.       
  24.     from = s;  
  25.     end = s + len;  
  26.     start = to = (unsigned char *) safe_emalloc(3, len, 1);  
  27.   
  28.     while (from < end) {  
  29.         c = *from++;  
  30.   
  31.         if (c == ‘ ‘) { 
  32.             *to++ = ‘+‘; 
  33. #ifndef CHARSET_EBCDIC 
  34.         } else if ((c < ‘0‘ && c != ‘‘ && c != ‘.‘) || 
  35.                    (c < ‘A‘ && c > ‘9‘) || 
  36.                    (c > ‘Z‘ && c < ‘a‘ && c != ‘_‘) || 
  37.                    (c > ‘z‘)) {  
  38.             to[0] = ‘%‘; 
  39.             to[1] = hexchars[c >> 4]; 
  40.             to[2] = hexchars[c & 15]; 
  41.             to += 3; 
  42. #else /*CHARSET_EBCDIC*/ 
  43.         } else if (!isalnum(c) && strchr("_-.", c) == NULL) { 
  44.             /* Allow only alphanumeric chars and ‘_‘, ‘‘, ‘.‘; escape the rest */ 
  45.             to[0] = ‘%’;  
  46.             to[1] = hexchars[os_toascii[c] >> 4];  
  47.             to[2] = hexchars[os_toascii[c] & 15];  
  48.             to += 3;  
  49. #endif /*CHARSET_EBCDIC*/  
  50.         } else {  
  51.             *to++ = c;  
  52.         }  
  53.     }  
  54.     *to = 0;  
  55.     if (new_length) {  
  56.         *new_length = to – start;  
  57.     }  
  58.     return (char *) start;  
  59. }  
  60. /* }}} */  

评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注