Nita Nita - 1 month ago 30
PHP Question

Google URL Shortener - not specified HTTP Referer

I have URL shortening script the was working well until I added website referrers to KEY restriction in API console (which i had to do). Now i dosen't return short url. I get following error:


Array ( [error] => Array ( [errors] => Array ( [0] => Array ( [domain]
=> usageLimits [reason] => ipRefererBlocked [message] => The request did not specify any referer. Please ensure that the client is sending
referer or use the API Console to remove the referer restrictions.
[extendedHelp] =>
https://console.developers.google.com/apis/credentials?project=XXXXXXXXX
) ) [code] => 403 [message] => The request did not specify any
referer. Please ensure that the client is sending referer or use the
API Console to remove the referer restrictions. ) )


My PHP:

<?php

$longurl = "http://example.com";

$api_key_google = "XXXX_API_KEY_XXXXX";
$curl = curl_init('https://www.googleapis.com/urlshortener/v1/url?key='.$api_key_google);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array('longUrl' => $longurl)));
$return = json_decode(curl_exec($curl), true);
curl_close($curl);

print_r($return);
echo $shortDWName = $return['id'];

?>


What Am I missing here? Thanks for your help in advance.

Answer

Try to add this line

curl_setopt($curl, CURLOPT_HEADER, 0);
// should add this line
curl_setopt($ch, CURLOPT_REFERER, '[your restriction domain]');