Rest API how to authentication via Basic Auth?

Viewed 19115

I want to create RESTful API with Basic Authorization.

How can i do it in php ? how can i get below String and Check authentication on php side via headers ?

Basic Zajkljask34jlksdlfkjds=

2 Answers

First you need to create .htaccess file if it's not already in existence. Now, you need to add the following lines:

RewriteEngine On
RewriteRule .* - [e=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Next, add the following lines of code in the PHP file in which you want to parse the information:

if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {

    if (strpos(strtolower($_SERVER['REDIRECT_HTTP_AUTHORIZATION']),'basic')===0)
        list($username,$password) = explode(':',base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));

}

Here you can see that the username and password are stored in $username and $password variable. Now, you can do whatever you want to do with these values such as checking against database - you can do that by adding the extra logic.

Related