How to shorten a url using php?

Member

by gilbert , in category: Third Party Scripts , 4 days ago

How to shorten a url using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 4 days ago

@gilbert 

You can shorten a URL using PHP by using a URL shortening service such as Bitly, TinyURL, or Google's URL Shortener API. Here is an example using the Bitly API:

  1. First, you need to create an account on Bitly and obtain an access token.
  2. Use the following code to send a request to the Bitly API and shorten a URL:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$access_token = 'YOUR_BITLY_ACCESS_TOKEN';
$long_url = 'https://www.example.com';

$api_url = 'https://api-ssl.bitly.com/v4/shorten';
$data = ['long_url' => $long_url];
$headers = [
    'Authorization: Bearer ' . $access_token,
    'Content-Type: application/json'
];

$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

$short_url = json_decode($response)->link;

echo 'Short URL: ' . $short_url;


Replace 'YOUR_BITLY_ACCESS_TOKEN' with your actual Bitly access token. This code sends a POST request to the Bitly API to shorten the specified URL and then extracts the shortened URL from the response.


Note: Make sure to have the cURL extension enabled in your PHP configuration to use this code.