Jareddlc
Jareddlc

Reputation: 349

Require password to view webpage [jQuery, JavaScript, or PHP]

I have a page that I would like to password protect. This page should be accessible if the user hits the URL www.webpage.com/page.php It will be emailed to the user along with a verification code.

I have most of the page written with jQuery. I would like to know how I can prevent access to the page without a proper password. After the user has entered proper password and has verified it will then display the content.

I tried doing something with jQuery dialog, and hiding the content then showing it after verification, however the user can view the content if they view the source of the page.

How should I go about doing so?

I'm just trying to avoid creating a new page. I guess I will have to use sessions.

Upvotes: 3

Views: 4008

Answers (3)

Mr. 14
Mr. 14

Reputation: 9528

If you just want a quick and easy solution, you can also consider using HTTP authentication with PHP. It can be as easy as the following

<?
header("Content-type: text/html; charset=utf-8");
if(empty($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Please input"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Please enter the correct username and password.';
    exit;
} else {
    echo "Username: ".$_SERVER['PHP_AUTH_USER']."<br>";
    echo "Password: ".$_SERVER['PHP_AUTH_PW']."<p>";
    $username = "demo";
    $password = "demo";
    if(($_SERVER['PHP_AUTH_USER'] != $username) || ($_SERVER['PHP_AUTH_PW'] != $password)) {
        echo "Login Failed!";
    } else {
        echo "You're in!";
    }
}
?>

You can also find a more elaborate implementation here.

Upvotes: 1

NullPoiиteя
NullPoiиteя

Reputation: 57312

yes, you can do this but if you protected the page by password only client side its not a good even ok idea since the user can modify the JavaScript/jquery for that you can load the content by ajax after verifying the password .

to prevent the access without the password don't load the data it the password doesn't verifying (since i think you are verifying the password by ajax)

Upvotes: 1

Fluffeh
Fluffeh

Reputation: 33504

You need to do the validation that they are using (the right) password in PHP and only then actually output the content to them. If they don't have the password, tying to hide it from visibility is a no-win scenario.

Commonly, Session variables are used for this. The verification script checks the user login/password and it it is accepted, assigns a session variable to the user.

Then in your actual code (for the secret page) you check against this session variable and if it is there, you go ahead and display the content to the user, if it isn't matched, you either display an error message or redirect the user off to another page through a header().

Upvotes: 0

Related Questions