title: login against ldap server
body: <p>i have a php login page using ldap, it works fine if the login is good(redirect to mainpage) and bad ( error message appears), but it also redirect me to the mainpage if i write any username without password. How can i correct it?</p>
  
  <p>Also i am not sure if the use of session_start is correct.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>&lt;?php
  
  if(isset($_POST['username']) &amp;&amp; isset($_POST['password'])){?&gt;
  
  
  
  &lt;?
  
  $adServer = "ldap://server.domain.local";
  
  $ldap = ldap_connect($adServer);
  $username = $_POST['username'];
  $password = $_POST['password'];
  
  $ldaprdn = 'Domain' . "\\" . $username;
  
  ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
  ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
  
  $bind = @ldap_bind($ldap, $ldaprdn, $password);
  
  
  if ($bind) {
      $filter="(sAMAccountName=$username)";
      $result = ldap_search($ldap,"ou=country,dc=domain,dc=local",$filter);
      ldap_sort($ldap,$result,"sn");
      $info = ldap_get_entries($ldap, $result);        
      session_start();               
      $_SESSION['username'] = $username;
       header("Location: /main.php");
       @ldap_close($ldap);
  } else {
      /**$msg = "Invalid email address / password";
      echo $msg;*/
  
      echo "&lt;center&gt;&lt;h2&gt;Failed authentication for &lt;span style='color: #000;'&gt;" . $username     . "&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;
                &lt;a href='login.php'&gt;Try again&lt;/a&gt;&lt;/center&gt;";
  
  }
  
  }else{
  ?&gt;
  
  &lt;?php } ?&gt; 
  </code></pre>
  
  <p>Thanks in advance!!</p>