KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Setting the expiration of a cookie
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: August 16, 2017

Here is a method to set the expiration of a cookie in a 4D Web Server application:

// --------------------------------------------------------------------------------
// Name: WEB_SET_COOKIE_EXP
// Description: Method will set the expiration of a cookie this exsisting or
// newly created.
// Input:
// $1 (TEXT) - Key of the cookie
// $2 (TEXT) - Value of the cookie
// $3 (BOOLEAN) - Secured cookie (True or False)
// $4 (LONGINT) - Number of hours or days to set the cookie expiration
// $5 (LONGINT) - Mode to set the hour or day (0 - hours, 1 - days)
// --------------------------------------------------------------------------------
C_TEXT($1;$Key_T)
C_TEXT($2;$Value_T)
C_BOOLEAN($3;$Secured_B)
C_LONGINT($4;$hoursOrDays)
C_LONGINT($5;$choiceHoursDays)
C_TEXT($HdrValue_T;$expires)
C_TIME($time)
C_DATE($date)

If (Count parameters=5)
  $Key_T:=$1
  $Value_T:=$2
  $Secured_B:=$3
  $hoursOrDays:=$4
  $choiceHoursDays:=$5
   
  If ($Secured_B)
   $Value_T:=$Value_T+"; HttpOnly"
  End if
   
  If ($choiceHoursDays=0) // Hours
   $time:=current time+(3600*$hoursOrDays)
   $expires:="expires="+String(Current date;Date RFC 1123;$time)
  Else
   $date:=Current date+$hoursOrDays
   $expires:="expires="+String($date;Date RFC 1123;current time)
  End if
   
  $HdrValue_T:="SET-COOKIE: "+$Key_T+"="+$Value_T+";"+$expires
   
  WEB SET HTTP HEADER($HdrValue_T)
End if


Here is an example of setting the cookie to expire in 4 hours:

WEB_SET_COOKIE_EXP("lang";"fr";false;4;0)



Here is an example of setting the cookie to expire in 2 days:

WEB_SET_COOKIE_EXP("lang";"fr";false;2;1)


Example of a cookie set and displayed in a browser: