Search code examples
phpzend-frameworksessionzend-session

PHP Zend Session code reverse-engineering explanation


I was looking through the code for Zend_Session to try and get a better understanding of how to implement session starting. Within the code, they do something that I don't quite understand.

$hashBitsPerChar = ini_get('session.hash_bits_per_character');          
if (!$hashBitsPerChar) {
    $hashBitsPerChar = 5;
}           
switch($hashBitsPerChar) {
    case 4: $pattern = '^[0-9a-f]*$'; break;
    case 5: $pattern = '^[0-9a-v]*$'; break;
    case 6: $pattern = '^[0-9a-zA-Z-,]*$'; break;
}           
if(!preg_match('#'.$pattern.'#', $id)){             
    session_id(md5(session_id()));              
    $regenerateId = true;
}

What I'm having difficulty understanding is why they have a pattern that has a not ( ^ ) and then if it does not match they create a temporary session id before starting the session. This to me doesn't make sense - why do they do a pregmatch against not having 0-9a-zA-Z-, ? I just don't quite understand whats going on here and would like to understand.

Thanks


Solution

  • The caret in the regular expression doesn't invert the pattern; it's an anchor to match the beginning of the line.

    Depending on the value configured for session.hash_bits_per_character, the method selects a specific regular expression (zero-or-more matches of either [0-9a-f], [0-9a-v], or [0-9a-zA-Z-,]) as a session identifier recognition pattern.

    If there was no match (!preg_match(...)) for that pattern against the current session identifier (if it didn't match one of the three patterns) then the session identifier is regenerated; the MD5 hash of the current session identifier becomes the new session identifier and a flag is set to indicate that the regeneration has occurred.