home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Connectivity / PPP / Docs / NeXTPPP_HTML / websale / parseurl.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-09-18  |  1.5 KB  |  82 lines

  1. /*
  2.  * parseurl.c
  3.  * A portable, simple but inefficient way of parsing URLs from searches
  4.  *
  5.  * i = parseurl(qs, v, r)
  6.  * qs is the encoded query string (getenv("QUERY_STRING"))
  7.  * f is the name of the field to look up
  8.  * r is where to return the result
  9.  * rs is the number of bytes allocated in r
  10.  * i returns 
  11.  */
  12.  
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15.  
  16. static int hexdig(i)
  17. int i;
  18. {
  19.     if ('0' <= i && i <= '9')
  20.         return i-'0';
  21.     else if ('A' <= i && i <= 'F') 
  22.         return i-'A'+10;
  23.     else return i-'a'+10;
  24.     }
  25.  
  26. static int decode(qs, r, rs)
  27. char *qs, *r;
  28. int rs;
  29. {
  30.     /* Decode one value up to the & or \0 */
  31.     while (1 < rs && *qs && *qs != '&') {
  32.         if (*qs == '+') {
  33.             *r++ = ' ';
  34.             qs++ ; rs--;
  35.             }
  36.         else if (*qs == '%') {
  37.             *r++ = hexdig(qs[1])*16+hexdig(qs[2]);
  38.             qs += 3; rs--;
  39.             }
  40.         else {
  41.             *r++ = *qs++; rs--;
  42.             }
  43.         }
  44.     *r = 0;
  45.     if (0 < rs) return 1;
  46.     return 2;
  47.     }
  48.         
  49. int parseurl(qs, v, r, rs)
  50. char *qs, *v, *r;
  51. int rs;
  52. {
  53.     if (qs == NULL) {
  54.         qs = getenv("QUERY_STRING");
  55.         }
  56.     if (qs == NULL || *qs == 0) return -1;
  57.     while (*qs) {
  58.         if (0==strncmp(v, qs, strlen(v)) &&
  59.             qs[strlen(v)]=='=')
  60.             return decode(qs+strlen(v)+1, r, rs);
  61.         while (*qs && *qs != '&') qs++;
  62.         if (*qs == '&') qs++;
  63.         }
  64.     return 0;
  65.     }
  66.  
  67. #if 0
  68. void main()
  69. {
  70.     char email[20];
  71.     int i;
  72.  
  73.     printf("content-type: text/plain\n\n");
  74.     printf("TEST RESULTS\n");
  75.     printf("getenv=%s\n", getenv("QUERY_STRING"));
  76.     i = parseurl(NULL, "emailaddr", email, sizeof(email));
  77.     printf("i=%d\n", i);
  78.     printf("email=%s\n", email);
  79.     exit(0);
  80.     }
  81. #endif
  82.