Tuesday, June 26, 2012

PHP Learning - How to Create Password Protected Page

Most often, visitors are required to enter username and password to view a page. You can create user auth either with HTTP and Apache or specify in PHP code. Today, let's take a look how to with HTTP and Apache.

You use instructions to Apache, called directives, to set up your authentication application. Directives allow you to specify the files that are password-protected and the valid user names and IDs. The simplest way to use Apache directives for authentication is to create a file called .htaccess

For example, I want to protect my folder called "user". Thus I will create a file called .htaccess. in that file, I specifies the following lines:

AuthUserFile c:\secret\.htpass

AuthGroupFile /dev/null

AuthName Accounting Department

AuthType Basic

Require valid-user

then in the Windows command prompt, i can type

c:\Apache\bin\htpasswd -c c:\secret\.htpass jeff

to create a username for Jeff (in order to do this, you need to go to your httpd.txt file and change "AllowOverride None" to "AllowOverride Authconfig")

Another way to create a page that requires user name and password is through using Http Auth in PHP. Unlike Http auth with Apache, Http auth with PHP have username and password stored in database, in my example, i will use Mysql (since it is my favorite database)

First, I want to create a database, called "Jefftest"

Create database Jefftest;

Then create a table in the database

CREATE TABLE User (

user_name CHAR(10) NOT NULL,

password CHAR(255) NOT NULL,

create_date DATE NOT NULL,

PRIMARY KEY(user_name) );

Then you can access the database from your PHP script with the MySQL functions that are built into PHP. In here, i won't tell you how to access Mysql by using php built-in function (I might in the future) since it is fairly complex to php beginners. But at least you got the idea of how this function is achieved by using HTTP with the apache server.


View the original article here

No comments:

Post a Comment