diff --git a/www/auth/login.php b/www/auth/login.php
index 4e106a8986d6bfb1df8875857af9e5dc2c5687a2..74291a79b8296566c7d0ce95dc3f0d156424c962 100644
--- a/www/auth/login.php
+++ b/www/auth/login.php
@@ -56,22 +56,49 @@ if (isset($_POST['username'])) {
 		} else {
 			$sr = ldap_read($ds, $dn, $config->getValue('auth.ldap.attributes'));
 			$ldapentries = ldap_get_entries($ds, $sr);
-			
 
+			/* Check if we have any entries in the search result.
+			 */
+			if($ldapentries['count'] == 0) {
+				throw new Exception('LDAP: No entries in the' .
+				                    ' search result.');
+			}
+
+			/* Currently we only care about the first entry. We
+			 * write a message to the error log if we have more.
+			 */
+			if($ldapentries['count'] > 1) {
+				error_log('LDAP: we have more than one entry' .
+				          ' in the search result.');
+			}
+
+			/* Iterate over all the attributes in the first
+			 * result. $ldapentries[0]['count'] contains the
+			 * attribute count, while $ldapentries[0][$i]
+			 * contains the name of the $i'th attribute.
+			 */
 			for ($i = 0; $i < $ldapentries[0]['count']; $i++) {
+				$name = $ldapentries[0][$i];
+
+				/* We currently ignore the 'jpegphoto'
+				 * attribute since it is relatively big.
+				 */
+				if ($name === 'jpegphoto') {
+					continue;
+				}
+
+				$attribute = $ldapentries[0][$name];
+
 				$values = array();
-				if ($ldapentries[0][$i] == 'jpegphoto') continue;
-				for ($j = 0; $j < $ldapentries[0][$ldapentries[0][$i]]['count']; $j++) {
-					$values[] = $ldapentries[0][$ldapentries[0][$i]][$j];
+
+				for ($j = 0; $j < $attribute['count']; $j++) {
+					$values[] = $attribute[$j];
 				}
-				
-				$attributes[$ldapentries[0][$i]] = $values;
+
+				assert(!array_key_exists($name, $attributes));
+				$attributes[$name] = $values;
 			}
 
-			// generelt ldap_next_entry for flere, men bare ett her
-			//print_r($ldapentries);
-			//print_r($attributes);
-			
 			$session->setAuthenticated(true);
 			$session->setAttributes($attributes);