Validate a PHP Session-ID

If you must work with a PHP Session-ID, sometimes it is better to check if these Session-ID is valid.

/**
 * Checks a Session-ID
 *
 * @author     Thomas Deuling <tdeuling@gmail.com>
 * @param      string $sessionID Session-ID
 * @return     boolean Is valid?!
 */
function checkSessionID($sessionID="") {
	return !preg_match('/^[a-zA-Z0-9]{26}$/', $sessionID);
}
  1. 616ojU this is delisious!
    xfather123

    • cmanley
    • August 21st, 2013

    This is the way to do it properly:

    /**
    * Validates the value (the session id) of a session cookie.
    * Useful for detecting potential hack attempts.
    * It is up to the caller to delete the cookie if necessary.
    * See also: http://lxr.php.net/xref/PHP_TRUNK/ext/session/session.c#php_session_valid_key
    *
    * @param string $value
    * @param boolean $debug
    * @return boolean
    */
    function session_validate($cookie_value, $debug = false) {
    // session.hash_function allows you to specify the hash algorithm used to generate the session IDs. ‘0’ means MD5 (128 bits) and ‘1’ means SHA-1 (160 bits). Since PHP 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.
    // session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are ‘4’ (0-9, a-f), ‘5’ (0-9, a-v), and ‘6’ (0-9, a-z, A-Z, “-“, “,”).
    if (!(isset($cookie_value) && is_string($cookie_value) && strlen($cookie_value))) {
    return false;
    }
    $bits = null;
    if (1) {
    $hash_function = ini_get(‘session.hash_function’);
    $hash_function_to_bits = array(
    0 => 128,
    1 => 160,
    );
    $bits = @$hash_function_to_bits[$hash_function];
    }
    $bits_per_char = ini_get(‘session.hash_bits_per_character’);
    $bits_per_char_to_charclass = array(
    4 => ‘0-9a-f’,
    5 => ‘0-9a-v’,
    6 => ‘0-9a-zA-Z\-,’, // this is also the default
    );
    $charclass = array_key_exists($bits_per_char, $bits_per_char_to_charclass) ? $bits_per_char_to_charclass[$bits_per_char] : $bits_per_char_to_charclass[6];
    $charlength = $bits ? (integer)ceil($bits / $bits_per_char) : ‘1,128’; // the last value is a somewhat arbitrary default
    $re = ‘/^[‘ . $charclass . ‘]{‘ . $charlength . ‘}$/’;
    $result = preg_match($re, $cookie_value);
    $debug && error_log(__FUNCTION__ . ‘ regexp: ‘ . $re . “\tresult: ” .intval($result));
    return $result;
    }

      • tdeuling
      • August 21st, 2013

      Nice! 🙂
      I will try it the next time.
      The other one was just a ‘quick-shoot’ in the past.

  1. No trackbacks yet.