1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Getting the cookie name & value, best practice?

Discussion in 'C, C++, C#' started by Monrox, Oct 12, 2010.

  1. Monrox

    Monrox Power Member

    Joined:
    Apr 9, 2010
    Messages:
    615
    Likes Received:
    579

    ....
    X-Powered-By: PHP/3.2.18
    Set-Cookie: PHPSESSID=fre54h546hgfngr5v2pg5d5dgh9gf; path=/
    Expires: Mon, 15 Jun 1999 09:00:00 GMT
    Cache-Control: private
    ....


    How to snatch the cookie content from the server response? Should I use a text array and read it line by line, some IndexOf / LastIndexOf combination or RegEx? Also if I go line by line, is it better to send a dedicated HEAD request instead of having to split hundreds of lines of the source html.

    I am really new to this server client communication and don't want to use lame logic due to ignorance :cool:
     
  2. confined

    confined Regular Member

    Joined:
    Jan 4, 2009
    Messages:
    216
    Likes Received:
    91
    PHP:
    $endhead strpos($content,"\r\n\r\n");
                
    $EL "\r\n";
                if(
    $endhead===FALSE){
                    
    $endhead strpos($content,"\n\n");$EL "\n\n";
                }
                if(
    $endhead===FALSE){
                    
    $endhead strpos($content,"\n\l\n\l");$EL "\n\l";
                }
                    
    $head substr($content,0,$endhead);
                    
    $headers explode($EL,$head);
                    foreach(
    $headers as $HEAD){
                        list (
    $key$value) = split(':'$HEAD2);
                        if (
    trim($key) == 'Set-Cookie') {
                            
    $value trim($value);
                            
    $p1 strpos($value'=');
                            
    $p2 strpos($value';');
                            
    $key substr($value0$p1);
                            
    $val substr($value$p1 +1$p2 $p1 -1);
                            
    $ret['cookies'][$key] = $val;
                        } else {
                            
    $ret['headers'][trim($key)] = trim($value);
                        }
                    }


    therefore $ret['cookies']['PHPSESSID'] would be fre54h546hgfngr5v2pg5d5dgh9gf


    whoops you posted in C# section... that's php.. still works.
     
    Last edited: Oct 12, 2010
  3. Monrox

    Monrox Power Member

    Joined:
    Apr 9, 2010
    Messages:
    615
    Likes Received:
    579
    Yeah well I just need the best way. The kind of language doesn't really matter for me as it's just different syntax.
    Here's how I'm doing it right now:

    Code:
     
    int StartCookie = (pageHTML.IndexOf("Set-Cookie: ") + 12);
    int EndCookie = pageHTML.IndexOf(";", StartCookie);
    int CookieLength = (EndCookie - StartCookie);
    string CookieString = pageHTML.Substring(StartCookie, CookieLength);