Using Authentication Header with file_get_contents in PHP

In PHP, file_get_contents() function is commonly used to get content of a file or a url and it works like a charm in normal scenario. If in case, the URL or file endpoint is under htaccess authentication, issue arises.

The following PHP script provides a simple function that can pass username and password in header to get the desired result :

Source Code :

function auth_file_get_contents($url){
  $username = {USERNAME};
  $password = {PASSWORD};
     
  $context = stream_context_create(array(
      'http' => array(
          'header'  => "Authorization: Basic " . base64_encode("$username:$password")
      )
  ));
  return file_get_contents($url, false, $context);
}

Follow this video for complete guidance :

Recommended For You

About the Author: Ritesh Ghimire

Ritesh is a Computer Engineer, Web Developer and an active cricket follower.