How to make simple PHP login script

Let`s create a simple PHP login script using WWW-Authenticate header, and session.
Note: if you want to use session in PHP, you must place session_start() in first row.

How it works

When there is not http_logged session, the script shows the login form. If the user enters the correct username and password the script shows the website, and sets http_logged to 1. If username and/or password is not correct, the user will receive an error message, and the script sets  http_logged to 0.

PHP_AUTH_USER - means the user name
PHP_AUTH_PW - means the password

The valid username is user, password is password for this script, you can set any username and password for your site. Also you can rename http_logged session anything you like.

In Basic realm you can define any message on your login form, for example: Enter password to access this page.

PHP

<?php
session_start();
if(!$_SESSION['http_logged'])
if ($_SERVER['PHP_AUTH_USER'] != "user" || $_SERVER['PHP_AUTH_PW'] != "password" ) {
$_SESSION['http_logged'] = 0;
header('WWW-Authenticate: Basic realm="Enter password to access this page."');
header('HTTP/1.0 401 Unauthorized');
exit;
} else {
$_SESSION['http_logged'] = 1;
}
?>

Demo »


Go Daddy


Related articles

Redirect www to non www with .htaccess RewriteRule

Redirect www to non www with .htaccess RewriteRule

05/12/2015

Redirect your websites visitors from www.domain.com to domain.com without www.

Email Validation

Email Validation

08/02/2013

Learn how to validate email on client side with HTML5, Javascript and on server side with PHP.

Generate Thumbnail on the Fly with PHP

Generate Thumbnail on the Fly with PHP

04/02/2013

In a previous artice I already showed you how to generate square thumbnails with PHP. Now I show you how to keep the original ratio of the image and how to control the alignment of the square image.


3 comments

D-Joy2013-01-03 21:20

Awesome login script :D

Tboy2012-12-18 19:20

Useful post, the script works fine :)

Greg2012-12-14 22:04

Nice and clean script! Great tutorial, thank you.

Leave a comment

We welcome any comment from you! Please keep in mind that comments are moderated and rel='nofollow' is in use. So, please do not use a domain as your name or a spammy keyword, or your comment will be deleted.

Name: *

E-mail: *

Message: *

Click on the flower *


Find us on Facebook

Tags

Get online with the world's Best - GoDaddy.com!

Back to Top