Benchmarkchart – php example code – part 4 – limiting access to admin page
Article describe way how to limit access into a admin page using header authentification. Before sending page data, user must by verified by providing username and password. Separate script authorize.php and adding third part into a appvars.php containing username and sha1 has for veriefied password added.
Using headers for authentication
Http headers authentifications provide simple way for limiting access for some resources on web. For further reading please wisit https://en.wikipedia.org/wiki/Basic_access_authentication.
For access to restricted resources user must provide correct username and pasword. If user enters these correctly, the browser goes ahed and sen page. This dialog between browser and server take place with headers, which are text messages with specific instruction on what is being requested or delivered.
Further reading about heder messages can be obtained from here, 4.10.2020.
Our authentification script looks like this
!isset($_SERVER[‚PHP_AUTH_PW‘]) ||
|| ( sha1($_SERVER[‚PHP_AUTH_PW‘]) != $password_sha) ) {
Access denied, you must enter a valid username and password to access this page!
For setting original username and password for reference and validation. Our appvar.php definition script was extended of third part as is shown next.
<!– **************************************************************** –><!– Part III | authorization constants –> <!-***************************************************************** –>
<?php
define(‚USERNAME‚, ‚administrator‚);
define(‚PASSWORD_SHA1‚, ‚02cc4d03794b3624b076e48a6d6d18b1f2af8dc1‚); // SHA value for wery weak demonstration password PassworD never use
in production environment!!!
// sha1 has code was generated for example by online app
http://www.sha1-online.com
?>
Adding authorize.php script on secured pages
Our authorize.php script must be added to begining of all restricted pages. Script must be executed as first code before any HTML content ransfer because enables or disables ability to access appropriate web resources.
Next segment of code contains example of including code with require_once(); php function.
For proper work of admin script is crucial to enable access to code on both admin.php and remove.php in same time. This requirement is fulfiled simply adding same code with same
header(‚WWW-Authenticate: Basic realm=“benchmark_admin„‚); .
After altering of our pages desribed way, our browser will promt for entering username and password as is shown on next picture.
Full code for further study
Most current version of aplication code can be obtained from github here.