- How to generate passwords for .htpasswd using PHP
- Method 1: Using crypt() function.
- Method 2: Using APR1-MD5 algorithm
- Share this:
- PHP file based authentication
- How to create a password for a .htpasswd file using PHP
- About HostingCanada®
- Our Mission
- Popular Hosting Providers
- How to encrypt password in PHP
- Encrypt password in PHP using md5
- Encrypt password in PHP using crypt()
- Encrypt password in PHP using password_hash()
How to generate passwords for .htpasswd using PHP
In my earlier post about .htaccess I had described about authentication using .htaccess and command to generate .htpasswd file. However, when we want to add passwords for many users that method will take too long, since we will have to add passwords for each user one at a time. However, there is an easier way to generate the .htpasswd file using PHP. In this post I will show the different algorithms which can be used to generate the .htpasswd file.
Method 1: Using crypt() function.
This uses method uses crypt() encryption for passwords. This used to be the default algorithm used by Apache (2.2.17 and older). The password generated by this method will not work on Windows systems as they use MD5 based passwords. This method is same as using the command :
htpasswd -d /usr/local/etc/apache/.htpasswd user1
The output of the code below can be directly added to the .htpasswd file.
Method 2: Using APR1-MD5 algorithm
MD5 encryption method is more secure than the crypt method. This is the default method since Apache 2.2.18. The password generated by using this method can be used on both Windows and Linux based systems. This method is same as using the command :
htpasswd -m /usr/local/etc/apache/.htpasswd user1
Here is a script which I created based on the function I found on Stack Overflow.
0; $i -= 16) < $text .= substr($bin, 0, min(16, $i)); >for($i = $len; $i > 0; $i >>= 1) < $text .= ($i & 1) ? chr(0) : $plainpasswd; > $bin = pack("H32", md5($text)); for($i = 0; $i < 1000; $i++) < $new = ($i & 1) ? $plainpasswd : $bin; if ($i % 3) $new .= $salt; if ($i % 7) $new .= $plainpasswd; $new .= ($i & 1) ? $bin : $plainpasswd; $bin = pack("H32", md5($new)); >for ($i = 0; $i < 5; $i++) < $k = $i + 6; $j = $i + 12; if ($j == 16) $j = 5; $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp; >$tmp = chr(0).chr(0).$bin[11].$tmp; $tmp = strtr(strrev(substr(base64_encode($tmp), 2)), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); return "$"."apr1"."$".$salt."$".$tmp; > // Password to be used for the user $username = 'user1'; $password = 'password1'; // Encrypt password $encrypted_password = crypt_apr1_md5($password); // Print line to be added to .htpasswd file echo $username . ':' . $encrypted_password;
user1:$apr1$e5cytbnu$ps.bh8zF0tkJpEgkGtYcf0
We can use either of the above methods, however, the preferred method is to use the MD5 algorithm, since it is more secure and also works on both Windows and Linux systems.
Using any of the above methods and a loop we can easily generate the passwords for many users. We can use loop similar to the following to generate the passwords to be added to the .htpasswd file.
// Array for usernames and password. $users = array(); // User 1 $users[0]['username'] = 'user1'; $users[0]['password'] = 'password1'; // User 2 $users[1]['username'] = 'user2'; $users[1]['password'] = 'password2'; // User 3 $users[2]['username'] = 'user3'; $users[2]['password'] = 'password3'; foreach($users as $user => $data) < $username = $data['username']; $password = $data['password']; // Encrypt password $encryptedpwd = crypt_apr1_md5($password); // Print line to be added to .htpasswd file $content = $username . ':' . $encryptedpwd; echo $content . '
'; >
user1:$apr1$9qrj2x80$p2L32fS0tO7JgwzUISW8b. user2:$apr1$hmay01vn$uIHCNVBgF5qH5jmNBIzw4/ user3:$apr1$v2tohm9c$3TtZAPuaD4dhPF62kPOwO/
By using PHP we can easily generate the code to be added to .htpasswd file for many users very easily. All the usernames and passwords in my examples are just sample users. Make use the username that you want and a different, more secure, password.
Update: Newer versions of Apache can use BCRPYT for password hash so here is another posts about Generating bcrypt .htpasswd passwords using PHP.
Share this:
PHP file based authentication
In this post, you will learn how to implement file-based authentication using the PHP programming language.
Some small sites do not have a need for a database back-end to store data. But security is still important, whether the site is big or small. They may have a requirement to authenticate some folder or file and want to set access credentials for that. We can handle such a case by using file based authentication using PHP.
To create the file-based authentication, first generate a username and password set by using the PHP password encryption technique md5(). The md5() function is commonly used to encrypt a string.
You can generate the username and password on click here.
Create a text file «auth.txt» and paste the generated username and password set as it is in the text file. Now, create a login form and copy and paste these code to authenticate the username and password from a text file.
rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> class="wrapper" style="width: 30%; margin: 0 auto;"> class="form-signin" action='#' method="post"> class="form-signin-heading">User Login
type="text" class="form-control" name="username" placeholder="username" required="" autofocus="" />
type="password" class="form-control" name="password" placeholder="Password" required=""/>
class="btn btn-small btn-primary btn-block" type="submit">Login function check_password($username, $password)< $pwd_file = 'auth.txt'; if(!$fh = fopen($pwd_file, "r")) die("p>Could not open password file");> $match = 0; $pwd = md5($password); while(!feof($fh)) < $line = fgets($fh, 4096); $user_pass = explode(":", $line); if($user_pass[0] == $username) < if(rtrim($user_pass[1]) == $pwd) < $match = 1; break; > > $match = 2; > if($match == '1') < echo "b>Login Success!/b>"; > if($match == '2') < echo "b>Login Failed!/b>"; > fclose($fh); > if($_POST['username']) < check_password($_POST['username'], $_POST['password']); > ?>
In the above code, we have used the fopen() function to open the text file and encrypt the entered password using the md5() function. We have matched the encrypted password with the stored password. If both passwords are the same, it prints a success message.
How to create a password for a .htpasswd file using PHP
A user emailed me and asked how to create a password for a .htpasswd file using PHP. It is actually very simple.
Below is a PHP script that generates a password for .htpasswd from the clear text password stored in $clearTextPassword.
Please note: For Apache servers running on Windows you have to use the htpasswd program to generate passwords, or use the htpasswd generator.
How to use the code:
- Copy the above the code and paste it into your favorite text editor (ie notepad).
- Change “some password” to the password you want to encrypt.
- Save the code in file called htpasswd.php.
- Upload htpasswd.php to your webserver.
- Execute the code by going to http://www.your-domain.com/htpasswd.php
- The outputted text is your encrypted password.
You can of course also use the htpasswd-generator if you don’t want your own script.
About HostingCanada®
hostingcanada.org was founded in 2017. The main goal of this website is to provide step-by-step instructions for hosting any website, blog or eCommerce site.
We also cover WordPress related questions, such as choosing the best WordPress hosting, how to speed up WordPress, and how to choose a domain name.
Located in Ottawa, Ontario. Canada.Read more
Our Mission
Our goal is to help Canadians understand hosting and empower them to start their own blogs or online businesses.
Our reviews are based on testing, live metrics (updated daily) and 100% unbiased opinions.Read more
Popular Hosting Providers
Earning disclosure: HostingCanada.org earns some commission from products and services discussed on this site. Read disclosure.
How to encrypt password in PHP
In this article, you will learn different ways to encrypt password using the PHP programming language. Generally, data is most vulnerable when it is being moved from one location to another. Encryption is the process through which information is encoded so it stays hidden from unauthorised users. It ensures private and sensitive data and can improve the security of communication between client apps and servers. Today, almost every application needs a password encryption technique to protect the sensitive information of its users.
PHP provides a range of different encryption methods. PHP has a hash algorithm to encrypt the password. The most commonly used functions for password encryption are md5(), crypt(), and password_hash().
Assume we have the registration form data in the POST, which includes the username and password. If we insert the same password as received in the POST into the database, this is not a secure way. If the database falls into the wrong hands, then they can misuse the data.
Encrypt password in PHP using md5
The MD5 hashing algorithm generates a 32-character string (hash hexadecimal number) for any word or phrase we give in the input. This is a one-way encryption algorithm. The password encrypted with this algorithm can never be decrypted. The md5 is the most commonly used encryption method. The md5() function is used to calculate the md5 hash of a string. The syntax of the md5() function is-
md5(string,raw)
Here, the string is the string to be encrypted, and the row is an optional parameter. It specifies the output format, which can either be TRUE or FALSE. The default is FALSE.
The given code encrypts the password value and stores it in the database.
$conn = new mysqli('hostname', 'username', 'password', 'databasename'); $pwd = $_POST['password']; $encrypted_pwd = md5($pwd); $username = $_POST['username']; $insert color: #0000ff;">$username', '$encrypted_pwd')"; if($conn->query($insert))< echo 'Data inserted successfully'; > else< echo 'Error '.$conn->error; > ?>
Encrypt password in PHP using crypt()
The crypt() function of PHP returns a hashed string using salt. This method generates a weak password without salt. It takes a second parameter for the salt, which is an optional parameter. The salt is a formatted string that tells the crypt() method which algorithm is used to do the hashing. It returns a hashed string using the DES, Blowfish, or MD5 algorithms. Make sure to specify a strong enough salt for better security.
There are many salt constants, but here we have used CRYPT_MD5. This generates a 12 characters salt.
$conn = new mysqli('hostname', 'username', 'password', 'databasename'); $pwd = $_POST['password']; if(CRYPT_MD5 == 1) < $encrypted_pwd = crypt($pwd, '$12$hrd$reer'); > $username = $_POST['username']; $insert color: #0000ff;">$username', '$encrypted_pwd')"; if($conn->query($insert))< echo 'Data inserted successfully'; > else< echo 'Error '.$conn->error; > ?>
Encrypt password in PHP using password_hash()
The password_hash() method of PHP is used to create a new password hash using a strong one-way hashing algorithm. It means that the only way to validate a hashed output is to pass the original value to the hashing algorithm and compare the results. This makes hashing perfect for storing user passwords. The password_hash() function is compatible with the crypt() function. It is implemented in PHP 5.1. Here is the syntax of password_hash().
password_hash(string, algorithm, options)
Here, string is the string to be encrypted, algorithm denotes the algorithm to use when hashing the password, and options is an associative array containing options.
The given PHP code encrypts the password value using the password_hash() and stores it in the database.
?php // Database connection $conn = new mysqli('hostname', 'username', 'password', 'databasename'); $pwd = $_POST['password']; // hash it with PASSWORD_DEFAULT $hash = password_hash($pwd, PASSWORD_DEFAULT); $username = $_POST['username']; $insert ="INSERT into an_users (id, username, password) VALUES ('', '$username', '$hash')"; if($conn->query($insert)) < echo 'Data inserted successfully'; >else< echo 'Error '.$conn->error; > ?>