php - 如何使用 C 和 G-wan 网络服务器设置和读取 cookie

标签 php c g-wan

在 php 中你可以设置一个 cookie

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

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

如何设置和读取cookie?

我似乎无法在网络上找到任何解释如何执行此操作的文章。其实c web开发的文章并不多

最佳答案

G-WAN tar ball 包含 2 个与 cookie 相关的示例源代码文件:cookie.c(设置 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')
}

和cookies.c(读取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;
}

关于php - 如何使用 C 和 G-wan 网络服务器设置和读取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30763253/

相关文章:

php - 为什么这个索引字符串会清除 $_SESSION 数组?

PHP/MySql 代码更简单更高效

java - 将 windows.h HANDLE 返回到 Java JNI

c - fscanf 上的段错误(核心已转储)

c - malloc() 不分配缓冲区大小

url-rewriting - 在 G-WAN 上为 .JPG 重写 URL

php - 在本地变量之前设置 $_SESSION 的奇怪 PHP 变量行为

php - 用户权限功能php的简便方法

java - GWAN 无法识别 Sun Java 7

无法让 redis 连接器与 g-wan 一起工作