Advertising sustains the DA. Ads are hidden for members. Join today

URL shortening using google api

Last updated on
30 April 2025

You are browsing documentation for an older version of Drupal, which is not supported any longer, and the information may not be correct. See current documentation for Contributed modules

You can write your own short code to get your url shortened by google apis, below is a snippet which does that:

function my_custom_url_shorten($long_url) {
  $service_url = 'https://www.googleapis.com/urlshortener/v1/url?key=******* your google url shorten api key *******';

  // Create cURL
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $service_url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("longUrl" => $long_url)));
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  // Execute the post
  $result = curl_exec($ch);

  // Close the connection
  curl_close($ch);

  // Return the result
  $curl_response = json_decode($result, true);

  $id = isset($curl_response['id']) ? $curl_response['id'] : false;

  return $id;
}

Help improve this page

Page status: Not set

You can: