@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 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.