How to set and read cookies using C and the G-wan web server

In php, you have to set a cookie by doing

Setting new cookie
=============================
<?php 
setcookie("name","value",time()+$int);
/*name is your cookie name
value is cookie value
$int is time of cookie expires*/
?>

Getting Cookie
=============================
<?php 
echo $_COOKIE["your cookie name"];
?>

      

How do you set and read a cookie?

I cannot find any articles on the internet explaining the hoe to do this. There aren't really many articles for web development c

+3


source to share


2 answers


The G-WAN tare ball includes 2 sample cookie related source files: cookie.c (set a cookie)

#include "gwan.h" // G-WAN exported functions

int main(int argc, char *argv[])
{
   // "Set-Cookie: Domain=.foo.com; Path=/; Max-Age=%u\r\n"
   const char cookie[] = "Set-Cookie: Max-Age=3600\r\n" // 1 hour
                         "Location: /?served_from\r\n\r\nblah\r\n";
   http_header(HEAD_ADD, (char*)cookie, sizeof(cookie) - 1, argv);

   return 301; // return an HTTP code (301:'Moved')
}

      



and cookies.c (reading cookies)

#include "gwan.h"
#include <stdio.h>
#include <string.h>

// ----------------------------------------------------------------------------
// where 'cookies' = "key1=value1; key2=value2;"
// ----------------------------------------------------------------------------
static kv_t parse_cookies(char *cookies)
{
  kv_t cookies_store;
  kv_init(&cookies_store, "cookies", 1024, 0, 0, 0);

  char *key, *val, *lasts = 0;
  for(;;)
  {
     key = strtok_r(cookies, "= ", &lasts);
     val = strtok_r(0, ";,", &lasts);

     if(!val) break; //no more cookies

     kv_add(&cookies_store, 
            &(kv_item){
             .key = key,
             .val = val,
             .flags = 0,
           });

     cookies = 0;
  }
  return cookies_store;
}
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  // using the client cookies (make sure that they are there)
  // http_t *http = get_env(argv, HTTP_HEADERS, 0);
  // kv_t cookies_store = parse_cookies(http->h_cookies);

  // using fixed cookies (for tests without client cookies)
  char cookies[] = "key=val;foo=bar"; 
  kv_t cookies_store = parse_cookies(cookies);

  char *val = kv_get(&cookies_store, "key", sizeof("key") - 1);

  printf("%s = %s\n", "key", val);

  kv_free(&cookies_store);
  return 200;
}

      

+1


source


Cookie is set as any other HTTP header: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#innerlink_set-cookie



You can find sample code in the gwan archive, here: gwan_linux64-bit / 0.0.0.0_8080 / # 0.0.0.0/csp

+1


source







All Articles