+ /**
+ * Return the true if the cookie is valid is valid. Otherwise,
+ * false. The uses a method similar to IE cookie security
+ * described here:
+ * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
+ * A better method might be to use a blacklist like
+ * http://publicsuffix.org/
+ *
+ * @param $domain String: the domain to validate
+ * @param $originDomain String: (optional) the domain the cookie originates from
+ * @return Boolean
+ */
+ public static function validateCookieDomain( $domain, $originDomain = null ) {
+ // Don't allow a trailing dot
+ if ( substr( $domain, -1 ) == "." ) {
+ return false;
+ }
+
+ $dc = explode( ".", $domain );
+
+ // Only allow full, valid IP addresses
+ if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
+ if ( count( $dc ) != 4 ) {
+ return false;
+ }
+
+ if ( ip2long( $domain ) === false ) {
+ return false;
+ }
+
+ if ( $originDomain == null || $originDomain == $domain ) {
+ return true;
+ }
+
+ }
+
+ // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
+ if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
+ if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
+ || ( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
+ return false;
+ }
+ if ( ( count( $dc ) == 2 || ( count( $dc ) == 3 && $dc[0] == "" ) )
+ && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
+ return false;
+ }
+ }
+
+ if ( $originDomain != null ) {
+ if ( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
+ return false;
+ }
+
+ if ( substr( $domain, 0, 1 ) == "."
+ && substr_compare( $originDomain, $domain, -strlen( $domain ),
+ strlen( $domain ), TRUE ) != 0 ) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+