Search code examples
phpfile-get-contents

How can in_array work while fetching values from external URL using PHP


I have following code which contains some keys and when someone want to get some info from my server they send that API param with the URL and then it validates with my API keys stored and returns output.

$get_api = $_GET['api'];
$api = array('api_key1','api_key2','api_key3','api_key4');

if(in_array($get_api,$api, true)){
   echo "Found";
} else{
   echo "Not found";
}

When someone pass following API param, they will see output as found when URL is following:

https://www.example.com/index.php?api=api_key1

However I have several servers where I have to host these API Keys. So I cannot manually go and add API keys every time when I have to add one. So I did the following thing. I tried to host API Keys on one server and every other server would look in that file and if found it would return found.

The code for that was:

API Hosted Code: (HTML)

'api_key1','api_key2','api_key3','api_key4'

Code which request API Keys: (PHP)

$get_api = $_GET['api'];
$fetch_keys = file_get_contents("https://www.example.com/path-to-keys.html");
$api = array($fetch_keys);  // fetching and putting that in array

if(in_array($get_api,$api, true)){
   echo "Found";
} else{
   echo "Not found";
}

However, it is not working. It is returning internal error. Please can anyone guide how can I solve it or is their any better way to do it. Thanks


Solution

  • Try $api= explode (',', $fetch_keys);