chriltola / mail

0 stars 0 forks source link

Ldap #9

Open chriltola opened 1 year ago

chriltola commented 1 year ago

To create a form login using PHP to an LDAP server, you can use the following steps:

  1. Create a HTML form that allows users to enter their username and password.

    <form method="post" action="login.php">
       <label for="username">Username:</label>
       <input type="text" id="username" name="username"><br>
    
       <label for="password">Password:</label>
       <input type="password" id="password" name="password"><br>
    
       <input type="submit" value="Login">
    </form>
  2. In the login.php file, retrieve the username and password from the form submission.

    $username = $_POST['username'];
    $password = $_POST['password'];
  3. Create a connection to the LDAP server using the ldap_connect() function.

    $ldapconn = ldap_connect("ldap.example.com");
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
  4. Bind to the LDAP server using the provided username and password.

    $ldaprdn = "cn=$username,ou=people,dc=example,dc=com";
    ldap_bind($ldapconn, $ldaprdn, $password);
  5. Check if the bind was successful using the ldap_errno() function.

    if (ldap_errno($ldapconn) == 0) {
       // Login successful
    } else {
       // Login failed
    }
  6. Close the connection using the ldap_close() function.

    ldap_close($ldapconn);
  7. Depending on the result of the bind, either redirect the user to a success page or display an error message.

Full code example:

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $ldapconn = ldap_connect("ldap.example.com");
        ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);

        $ldaprdn = "cn=$username,ou=people,dc=example,dc=com";
        ldap_bind($ldapconn, $ldaprdn, $password);

        if (ldap_errno($ldapconn) == 0) {
            // Login successful
            header('Location: success.php');
            exit();
        } else {
            // Login failed
            $error = "Invalid username or password";
        }

        ldap_close($ldapconn);
    }
?>

<form method="post" action="login.php">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username"><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password"><br>

    <input type="submit" value="Login">
</form>

<?php if (isset($error)) { ?>
    <p><?php echo $error; ?></p>
<?php } ?>