Q:

PHP user authentication like a router login

how to create user authentication in php just the same way when we try to login to a router. 

when i enter the url for example www.example.com/portal there should be a prompt like the above image asking username and password. 
what type of authentication is this. how to code that in php.
NOTE: i have to full control of the server that i run. so is there any special module that needs to be installed i can do that.

A:

This is called Basic Auth.  See this example from the documentation:
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

http://php.net/manual/en/features.http-auth.php
Essentially, you send the right headers with the status code of 401 Unauthorized.  the browser sees this along with your WWW-Authenticate header and prompts the user for you.  Once this is done, you are able to see the username and password in $_SERVER['PHP_AUTH_USER'] as well as $_SERVER['PHP_AUTH_PW'].
You should know though that if you are using basic auth, the username/password are sent plaint-text.  You must use HTTPS if you want any sort of security.  Also, depending on your application, you will see that there is no way to effectively "log out".  Most browsers remember the username/password for the entire session, and send it with every subsequent request.

