Jump to content
xisto Community
TavoxPeru

A Simple Checking & Validation PHP Script

Recommended Posts

Hi, there is sometimes that you need to password protect a directory in your site but you dont have access to a database or you dont need it because only a few users will access this directory, well the following script i develop will help in this situation.

 

With only 2 files you can implement a basic security, the first file is a simple txt file where you store your users information and the second file is the php script. You can name the files whatever you want and can be used in any site with php support.

 

The users.txt file: In this file simply put one line at the time your users information like this:

username1|userpassword1

username2|userpassword2

.

.

usernamen|userpasswordn

 

The chksec.php file: This file is the one that implements the basic security, here is the code:

<?phpif(!isset($_SERVER['PHP_AUTH_USER'])){	Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");	Header("HTTP/1.1 401 Unauthorized");	echo "Authorization Required.";	exit();}$theFile=file("users.txt");$nUsers=sizeof($theFile);$i=0;$validated=FALSE;while ($i<$nUsers && !$validated){	$aFields=explode("|",$theFile[$i]);	if (($_SERVER['PHP_AUTH_USER']==$aFields[0])&&($_SERVER['PHP_AUTH_PW']==chop($aFields[1]))) $validated=TRUE;	$i++;}if(!$validated){	Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");	Header("HTTP/1.1 401 Unauthorized");	echo "Authorization Required.";	exit();}?>

Thats it, to work you just need to include this file in another php file. For example:

<?phpinclude("chksec.php");echo "Welcome back " . $_SERVER['PHP_AUTH_USER'];?>
Best regards,

Share this post


Link to post
Share on other sites

Nice script. I like how you used http authentication, which IMO is the proper way of doing it. Cookies and sessions are a bit... Well you know , they work on some cases are not particularly secure.

Share this post


Link to post
Share on other sites

I like this except for the usage of the plain text file, if you were to do that, you should encode/encrypt your usernames and encrypt passwords, since having the username and password like this is not good, and encoding/encrypting the username eliminates half the problems while encrypting the password eliminates the other half.You should really be using htpasswd for this, that's what their purpose is for and that has it's own encrypting methods for the file.If you want the code for that method, I could write it up, strangely it's not different from your text file method, the only thing is we have encryption to work with.Cheers,MC

Share this post


Link to post
Share on other sites

I like this except for the usage of the plain text file, if you were to do that, you should encode/encrypt your usernames and encrypt passwords, since having the username and password like this is not good, and encoding/encrypting the username eliminates half the problems while encrypting the password eliminates the other half.
You should really be using htpasswd for this, that's what their purpose is for and that has it's own encrypting methods for the file.

If you want the code for that method, I could write it up, strangely it's not different from your text file method, the only thing is we have encryption to work with.

Cheers,

MC

Yes you are right, i know that limitation and if you know the name of the txt file you get the user/password information and your security is fall down, if you do and post the code for the encryption method i think every body will very grateful.

regards,

Share this post


Link to post
Share on other sites

So I went ahead and created a method that can make use of .htpasswd.

 

You can still use the above code the alterations just differ in the handling of the file, so I created the htpasswd checking in a separate file:

 

htpasswd.inc.php

 

<?phpdefine('HTPASSWD','.htpasswd');function load_htpasswd(){  if(file_exists(HTPASSWD) && filesize(HTPASSWD) > 0)  {	$htpasswd = file(HTPASSWD);	$auth = array();	foreach($htpasswd as $h)	{	  $array = explode(':',$h);	  $user = $array[0];	  $pass = chop($array[1]);	  $auth[$user] = $pass;	}	return $auth;  }  else	return array();}function sha1_htpasswd($pass){  return '{SHA}' . base64_encode(pack('H*', sha1($pass)));}//function md5mod_htpasswd($pass)//{//  return 'I wonder where apache leaves this algorithm in their source, since I can not seem to work it out';//}function valid_user($userpass, $user, $pass){  if(!isset($userpass[$user]))	return false;  $test = $userpass[$user];  if(strcmp(substr($test,0,5),'{SHA}') == 0)	return (strcmp(sha1_htpasswd($pass),$test) == 0);//  else if(md5mod_htpasswd($pass))//	return (strcmp(md5mod_htpasswd($pass),$test) == 0);  else	return (strcmp(crypt($pass, substr($test,0,CRYPT_SALT_LENGTH)),$test) == 0);}?>

and to use it as is:

 

<?php// These are required...function_exists('valid_user') || require('htpasswd.inc.php'); $userpass = load_htpasswd();// ... End of requirements// Below is just a test example.if(valid_user($userpass, 'username', 'password'))  echo 'User is valid';else  echo 'User is not valid';?>

The only problem I have with this code is Apache's modified MD5 algorithm, I don't seem to be able to figure this out, or locate anyone who has this, so the only other option would be using system calls, but I won't do this method. So it will only work with SHA-1 (strong) and Crypt (weak).

 

This can be dropped into the above code (by TavoxPeru) which replaces everything after the first if(statement) and before the if(!validated) where you would change that to be:

 

if(!valid_user($userpass,$_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']))

Hopefully there's no errors, I tweaked some of the code in this thread, so I could have caused some errors.

 

I probably should have added a method to write an .htpasswd file and generate a hash for the password, though all it requires is creating/appending to .htpasswd a file that looks like:

 

username1:the_encoded_hashusername2:the_encoded_hash

Where the encoded hash is basically sending the plain password to the sha1_htpasswod('plain password') function to generate the password and storing that in the file, you could use crypt but it is a weak encryption. Could use a plain text file too, but you do not want to allow access to it, which is why you use .htpasswd, since you can not view these files online (well you should not be able to).

 

Cheers,

 

MC

Share this post


Link to post
Share on other sites

Thanks mastercomputers great code. I go ahead and implement your changes to my script and works fine and also i include the use of the defined() and define() functions to allow direct access to the included file only by the parent script as discussed here:CMS103 - Securing Your Website.

 

The new chksec.php:

<?phpdefined( 'MY_ACCESS_CODE' ) or die( 'Direct Access to this location is not allowed.' );function_exists('valid_user') || require('htpasswd.inc.php'); $userpass = load_htpasswd();if(!isset($_SERVER['PHP_AUTH_USER'])){	Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");	Header("HTTP/1.1 401 Unauthorized");	echo "Authorization Required.";	exit();}if(!valid_user($userpass,$_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])){	Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");	Header("HTTP/1.1 401 Unauthorized");	echo "Authorization Required.";	exit();}?>
This is the new test file:
<?phpdefine( "MY_ACCESS_CODE", true );include("chksec.php");echo "Welcome back " . $_SERVER['PHP_AUTH_USER'];?>
I have a couple of questions, how do you do to implement a counter of login attempts??? for example only allow 3 login attempts, and do you have the method to write an .htpasswd file and generate a hash for the password??? If its true please post it to complete the script.

 

Best regards,

Share this post


Link to post
Share on other sites

I dont know if this the correct way to post this enhancement so to the admins please let me know if im wrong ok???.

In my previous post i drop a question related to how to implement a login counter attempts, for example 3 login attempts. Well, i go ahead and finish the script to support this behavior. So, if you want to implement this you only need to insert before line 2 of the chksec.php script the following code:

session_start();if (!isset($_SESSION['access_count'])) {	$_SESSION['access_count']=1;}else {	$_SESSION['access_count']++;}if($_SESSION['access_count']>3) {	unset($_SESSION['access_count']);	$_SESSION = array(); // reset session array	session_destroy();   // destroy session.	die( 'You exceed the maximum number of login attempts.' );}
That's it :(

Best regards,

Share this post


Link to post
Share on other sites
Validating unix credential using PHP scriptA Simple Checking & Validation PHP Script

Hi ...

I have a simple htm page in which I get the username and password.

I am trying to validate this entered value with the user name and password stored in UNIX /etc/passwd in format username1|passwd1, using a simple java script.Can anyone please help me out in this..Its really urgent.

Thanks you in advance!

 -reply by Priya

Share this post


Link to post
Share on other sites
Validating unix credential using PHP scriptA Simple Checking & Validation PHP ScriptHi,I have a simple html page where I get the username and password.I have to validate this values against the username and password stored in UNIX /etc/passwd in the format username1:Password1 using some script..Can you please help me with this.. Its really urgent..Thanks you so much in advance..-reply by Priya

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.