PHP easy login popup with server auth

PHP easy login popup with server auth
PHP easy login popup with server auth

Simple function for private and secure content page. Create login alert popup using PHP PHP_AUTH_USER and PHP_AUTH_PW.

Process is simple, if user enter wrong credential, page will display message and stop page execution with 401 error code.

Implementation is simple, just add checkPageAuth function in function file and call it in page beginning. Once user enter proper credential, page available for user.

Add function to common function file

Just change PHP_AUTH_USER and PHP_AUTH_PW value with your desired secure credential.

function checkPageAuth()
{
	if (empty($_SERVER['PHP_AUTH_USER'])
	|| empty($_SERVER['PHP_AUTH_PW'])
	|| $_SERVER['PHP_AUTH_USER'] != 'test'
	|| $_SERVER['PHP_AUTH_PW'] != 'test') {
		header('WWW-Authenticate: Basic Realm="Authenticate Area"');
		header('HTTP/1.0 401 Unauthorized');
		echo 'You must provide the proper credentials!';
		exit;
	}
}

Use function in private page

checkPageAuth();

//this will print if user provide proper credential
echo 'This is private content!';