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”.

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

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

<h1>Login</h1> 
<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" /> 
</form>

<?php 
}
else { 
?> 

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

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 config.inc file (or equivalent).

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: