reading cookie value issue

Maxim Dounin mdounin at mdounin.ru
Tue Apr 26 13:08:25 UTC 2016


Hello!

On Tue, Apr 26, 2016 at 05:07:19PM +0530, Pankaj Chaudhary wrote:

> Hi,
> 
> I have requirement to create own cookie  based on input  and wirte the that
> cookie in header.
> whenever i need that i can read from header and use it.
> 
> 
> for example:-
> 
> I have created my own cookie "thissomevalue" worte in header and later the
> same read from header.
> 
> Please check my code and let me know why i am not able to read the value
> from header.
> 
> Below code snippet to set header value in request header:-
> 
> ngx_table_elt_t *cookie;
> cookie = ngx_list_push(&r->headers_in.headers);
> cookie->lowcase_key = (u_char*) "cookie";
> ngx_str_set(&cookie->key, "Cookie");
> ngx_str_set(&cookie->value, "somevalue");
> cookie->hash = ngx_crc32_long(cookie->lowcase_key, cookie->key.len);

Note: you are not expected to modify request headers 
(r->headers_in).  Doing so will likely lead to segmentation 
faults.

If you want to provide your own cookie for a backend server, 
consider using proxy_set_header instead, see 
http://nginx.org/r/proxy_set_header.

> Below code snippet to read set value from header:-
> 
> ngx_http_core_main_conf_t   *clcf;
> ngx_str_t                   *type;
> ngx_uint_t                   key;
> ngx_str_t    val = ngx_string("cookie");
> clcf = ngx_http_get_module_main_conf(r, ngx_http_core_module);
> key= ngx_hash_key_lc(val.data, val.len);
> type = ngx_hash_find(&clcf->headers_in_hash, key,  val.data, val.len);
> 
> if (type != NULL)
> {
> ngx_table_elt_t *test_val;
> test_val= ngx_list_push(&r->headers_out.headers);
> test_val->lowcase_key = (u_char*) "test_val";
> ngx_str_set(&test_val->key, "Test_Val");
> ngx_str_set(&test_val->value, type->data);
> test_val->hash = ngx_crc32_long(test_val->lowcase_key, test_val->key.len);
> }

Structures stored in cmcf->headers_in_hash are ngx_http_header_t, 
see ngx_http_headers_in[] array in src/http/ngx_http_request.c.  
It is not expected to contain header value.  In case of the Cookie 
header, it's expected to contain the header name, function to 
handle the header during reading request headers from a client, 
and an offset of r->headers_in.cookie.

If you want to find out how to read a cookie as got from client, 
consider looking at the ngx_http_variable_cookie() function in 
src/http/ngx_http_variables.c.

-- 
Maxim Dounin
http://nginx.org/



More information about the nginx-devel mailing list