Generating .htpasswd Files in PHP

Learn how to create and manage .htpasswd files for Apache authentication using PHP.

Introduction

The .htpasswd file is used by Apache to store usernames and password for HTTP authentication. This file is usually placed in a directory that is protected from direct web access. PHP's crypt() function can be used to encrypt passwords in a way that's compatible with Apache's .htpasswd file.

Creating a New .htpasswd File

Use the following PHP script to create a new .htpasswd file with a username and a password:

<?php
$username = 'myUsername'; // Replace with your username
$password = 'myPassword'; // Replace with your password

$encryptedPassword = crypt($password, base64_encode($password));
$htpasswdContent = $username . ':' . $encryptedPassword;

file_put_contents('.htpasswd', $htpasswdContent);
?>
            
Appending a User to an Existing .htpasswd File

To add a new user to an existing .htpasswd file, you can append the username and encrypted password to the file:

<?php
$username = 'newUser'; // Replace with the new username
$password = 'newPassword'; // Replace with the new password

$encryptedPassword = crypt($password, base64_encode($password));
$htpasswdContent = "\n" . $username . ':' . $encryptedPassword;

file_put_contents('.htpasswd', $htpasswdContent, FILE_APPEND);
?>