やりたいこと
Googleの短縮URL(http://goo.gle/ のやつ)をPHPから呼び出したい。
前提
Developer Console からURL Shortener APIを有効にしておくこと。
サンプルコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
//$googleApiKey: GoogleのAPI キー //$longUrl : 元のURL //$shortUrl : 短縮したURL $ch = curl_init(); //取得するURL curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=' . $googleApiKey); //ヘッダの内容を出力しない curl_setopt($ch, CURLOPT_HEADER, false); //curl_exec()の返り値を文字列で取得する curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //HTTPヘッダの配列 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //POSTで送信する curl_setopt($ch, CURLOPT_POST, true); //POSTで送信するデータ(json形式) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('longUrl' => $longUrl,))); //リファラーを指定しないとipRefererBlockedエラーでコケる(Developer Consoleでリファラー制限してる場合) curl_setopt($ch, CURLOPT_REFERER, 'http://example.com/ALLOWED-REFERER-URL/'); $response = curl_exec($ch); curl_close($ch); $json = json_decode($response); //短縮URL $shortUrl = $json->id; |
Developer Consoleでリファラー制限を入れたところ、「CURLOPT_REFERER」を指定しないと「ipRefererBlocked」というエラーになってしまった。(さくらのレンタルサーバ スタンダード)
「http://example.com/ALLOWED-REFERER-URL/」はDeveloper Consoleで許可してあるURL(ホスト名)を入れる。