user3733831
user3733831

Reputation: 2936

Website access protect by password

I am trying to create a password protected website. Here I want to do if a user first time visit to my website then need to insert password to access my website. First time they entered the password they can freely access my website.

This is how I do it using javascript and php:

<?php if($page == 'index'): ?>
    <script language="Javascript">
            //prompt.
            var password;
            var correctPass = "123456"; 
            password = prompt("Enter in the password:","");

            if(password == correctPass) {
                    alert('click OK to view this site');
            } else {
                    window.location = "http://google.com"
            } 
            //->
    </script>               
<?php endif; ?>

This is working but my problem is if user go to the index page again they need to insert the password.

can anybody tell me how I fix this issue. Thank you.

Upvotes: 0

Views: 3542

Answers (3)

kojow7
kojow7

Reputation: 11424

Do not do this in JavaScript. Anyone can look at your source code and see the password. Do the password check in PHP instead. Then use $_SESSION variables to save the state while they are on your site. You may also want to use $_COOKIE variables for long term access, but just $_SESSION by itself is generally preferred in most cases for password access.

An alternate way to do it is with your web server. For example, if you are using Apache you can create a .htaccess file at the root of your website to ask for a name and password. That way you don't even need to code anything.

To do the second option, create a file called .htaccess in the root of your web directory. In the file put this in:

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /opt/passwords/.htpasswd
Require valid-user

(where /opt/passwords is a directory location outside of your web directory. It can be anywhere you want, you just want to make sure it is not anywhere within your web directory (otherwise it will be available for public viewing)).

In that directory, create a file called .htpasswd. This file will simply take a username and encrypted password. This page will allow you to create your name with password encryption: http://www.htaccesstools.com/htpasswd-generator/ . Just paste that into your .htpasswd file.

With that said, any password you use can be intercepted if you are only using http and not https, but setting up https is a bit difficult if you haven't done it before.

Upvotes: 7

jision
jision

Reputation: 181

first of all are you putting the plain password in java script itself??? never do that and also

if($page == 'index')

always constructs to true so the logic wont work use cookies or session

Upvotes: 0

venca
venca

Reputation: 1222

This is not safe. User can have disabled JS.

One of correct ways is to use http auth.

Upvotes: 1

Related Questions