Tech Tip: Utility Methods for retrieving HTTP Headers and a HTTP Cookies
PRODUCT: 4D | VERSION: 12.2 | PLATFORM: Mac & Win
Published On: May 27, 2011
A web cookie (aka a browser cookie and HTTP cookie) is a piece of text stored on a user's computer by their web browser. It can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing text data.
When an HTTP request is made to a Web Server, the browser includes the site cookies in the request header. From within the 4D environment (e.g. On Web Connection), the request header can be obtained with the command GET HTTP HEADER. Here is a wrapper method that loads all HTTP headers and returns a specific HTTP header value as the result.
// Method: UTIL_WEB_GetHeaderVar // Description // Return the value of the web header request // // Input // $1 - Name of the Header // Output // $0 - Value of the Header // ---------------------------------------------------- C_TEXT($0;$1;$headerName_t) C_LONGINT($foundat_l) ARRAY TEXT(web_requestHeaderNames_at;0) ARRAY TEXT(web_requestHeaderValues_at;0) GET HTTP HEADER(web_requestHeaderNames_at;web_requestHeaderValues_at) If (Count parameters>=1) $headerName_t:=$1 $foundat_l:=Find in array(web_requestHeaderNames_at;$headerName_t) If ($foundat_l#-1) $0:=web_requestHeaderValues_at{$foundat_l} End if End if |
Using the result of the method UTIL_WEB_GetHeaderVar, the cookie value can be extracted from the cookie string. Here is the method that does just that:
// Method: UTIL_WEB_GetCookie // Description // Get a cookie value for the given cookie name // // Input // $1 - Cookie name // Output // $0 - Cookie value // ---------------------------------------------------- C_TEXT($1;$targetCookie_t) C_TEXT($0;$cookies_t) C_LONGINT($position_l) If (Count parameters>=1) $targetCookie_t:=$1+"=" // *** Get all Cookie values in one string $cookies_t:=UTIL_WEB_GetHeaderVar ("Cookie") If (Length($cookies_t)>0) // *** Remove all string from the beginning up to the cookie keyword $position_l:=Position($targetCookie_t;$cookies_t) If ($position_l>0) $cookies_t:=Delete string($cookies_t;1;$position_l-1) Else $cookies_t:="" End if // *** Remove all string after the next semicolon $position_l:=Position(";";$cookies_t) If ($position_l>0) $cookies_t:=Substring($cookies_t;1;$position_l-1) End if // *** Remove all string from the begining up to the = sign $position_l:=Position("=";$cookies_t) If ($position_l>0) $0:=Delete string($cookies_t;1;$position_l) End if End if End if |
Here is an example call to the method:
// Method: On Web Connection $SessionID_t:=UTIL_WEB_GetCookie("SessionID") |