Gabriel Stein
Gabriel Stein

Reputation: 478

Hide/Convert sensitive info within img src or link

I am working with an XML API provider. They are providing me with certain image sources.

<img src="http://api-provider.com/image/?key=YOUR_KEY&id=ID"/>

Now to get any image I have to provide the key I am using for the API. So someone could simply look at the page source and get the key.

Is there anyway to bypass this and hide the key somehow?

Upvotes: 1

Views: 280

Answers (1)

Ghulam Ali
Ghulam Ali

Reputation: 1935

You can make a php file to load the image and put the API Key in your php file so that API Key will not be readable by others like this:

$API_Key = "Your_API_Key_Here";
$url = "http://api-provider.com/image/?key={$API_Key}&id={$_GET['id']}";
header('Content-type: image/jpeg');
readfile($url);

Then in your Image src tag put your own link: http://yourdomain.com/get_image.php?id={$Image_Id}

But it will use your server resources as the Image would be read from your server. Also if someone gets this URL he can use this without API Key so it will not be different than showing the API Key in URL at the first place, maybe you can verify the Session and then display the image.


As pointed by @miken32 to ensure that user is not trying to use your server directly, you can multiply with a random number and then do base64_encode to the id. Like this:

$Image_Src = "http://yourdomain.com/get_image.php?id=".base64_encode($Image_Id*18);

and in your PHP file before reading the image first verify that the id is a valid number by reversing the encoding you did above.

$Image_Id = $_GET['id'];
$Image_Id = base64_decode($Image_Id);
if (is_numeric($Image_Id)){
   $Correct_Image_Id = $Image_Id / 18;
   if ($Correct_Image_Id > 0){
      //read image here
   }
}

Upvotes: 2

Related Questions