Created
December 6, 2018 09:46
-
-
Save snorpey/2f61bbec09b5a9b6a0e5986f6116a9f9 to your computer and use it in GitHub Desktop.
gernerate htpasswd and htaccess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// this script generates a .htaccess and .htpasswd files in a folder (if they don't already exist) | |
// just upload protect_folder.php and open it the browser. | |
$user = 'myuser'; | |
$password = 'mypasswort'; | |
$encrypted_password = crypt( $password, base64_encode( $password ) ); | |
$folder_path = dirname( __FILE__ ); | |
$htaccess_path = $folder_path . DIRECTORY_SEPARATOR . '.htaccess'; | |
$htpasswd_path = $folder_path . DIRECTORY_SEPARATOR . '.htpasswd'; | |
$access_text_parts = [ | |
'AuthType Basic', | |
'AuthName "Password Protection"', | |
'AuthUserFile ' . $folder_path . DIRECTORY_SEPARATOR . '.htpasswd', | |
'Require valid-user' | |
]; | |
$access_text = implode( "\n", $access_text_parts ); | |
$pwd_text = $user . ':' . $encrypted_password; | |
if ( ! file_exists( $htaccess_path ) ) { | |
createFile( $htaccess_path, $access_text ); | |
} else { | |
if ( strpos( file_get_contents( $htaccess_path ), 'AuthType Basic' ) === false ) { | |
appendToFile( $htaccess_path, "\n" . $access_text ); | |
} | |
} | |
if ( ! file_exists( $htpasswd_path ) ) { | |
createFile( $htpasswd_path, $pwd_text ); | |
} else { | |
if ( strpos( file_get_contents( $htpasswd_path ), $user . ':' ) == false ) { | |
appendToFile( $htpasswd_path, "\n" . $pwd_text ); | |
} | |
} | |
function createFile ( $file_path, $content ) { | |
$file = fopen( $file_path,'wb'); | |
fwrite( $file, $content ); | |
fclose( $fp ); | |
} | |
function appendToFile ( $file_path, $content ) { | |
$file = fopen( $file_path,'a+'); | |
fwrite( $file, $content ); | |
fclose( $fp ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment