password protect a page with PHP

Password protection for a single page. Visitors are required to enter a password and username into a login form to view the page content. By default the password entry form is displayed, unless the both the password and username match; in that case the “protected content” is displayed. As this is served from server side, the protected content is secure at your end and will not display using “View Source”.

// Define your username and password
$username = "someuser";
$password = "somepassword";

if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) { 

<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="txtUsername">Username:</label>
<input type="text" title="Enter your Username" name="txtUsername" />
<label for="txtpassword">Password:</label>
<input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" /> 

else { 

<p>This is the protected page. Your private content goes here.</p>

This is a simplistic demonstration of the concept so, to maintain security on a live site, it would be best to store the username and password details in a file (or equivalent).


About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: