Apache web folder protection by setting username and password using php

Posted on 30 Ocak 2012 in İnternet, Programlama by

Hi apache people 🙂
While i was looking for a sample code to protect my web folders by setting username and password, i could not find appropriate code chunks. So i wrote my own http folder access codes using php for htaccess and htpasswd. htaccess simply points to which password file should be used. htpasswd contains the username and password to be used. For further information htpasswd can be located outside of the public_html folder to ensure users can not view content. htpasswd may contain more than one username and password information. In my case just i will use the protected folder. Therefore no problem for me 🙂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
     public static function encrypt ($username, $password) {
        $access = ".htaccess";
        $FileHandleAccess = fopen($access, 'w') or die("can't open file");
        $info = "AuthUserFile ./.htpasswd\nAuthType Basic\nAuthName \"My Secret Folder\"\nRequire valid-user";
        fwrite($FileHandleAccess, $info);
        fclose($FileHandleAccess);
 
        $passw = ".htpasswd";
        $ourFileHandle = fopen($passw, 'w') or die("can't open file");
        $stringEncrypted =crypt($password, base64_encode($password));
        $header = "# protect the htaccess file\n<files .htaccess>\norder allow,deny\ndeny from all\n</files>\n";
        fwrite($ourFileHandle, $header.$username.":".$stringEncrypted);
        fclose($passw);
     }

Please give us your valuable comment

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image

This site uses Akismet to reduce spam. Learn how your comment data is processed.