Table of Contents
You can easily create a URL shortener thanks to the service called TinyURL. In this post, we'll create a PHP script that will create a TinyURL from a long URL using their API.
TinyURL is a free service that allows you to create a short URL from a long URL. For example, it can turn:
BASHhttps://sabe.io/blog/php-create-tiny-url
into:
BASHhttps://tinyurl.com/yyh5vqnv
To interface with their API, we will use the cURL library. We will make a call to their API and get back the short URL.
The function get_tiny_url, looks like this:
PHPfunction get_tiny_url($url) {
$api_url = 'https://tinyurl.com/api-create.php?url=' . $url;
$curl = curl_init();
$timeout = 10;
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $api_url);
$new_url = curl_exec($curl);
curl_close($curl);
return $new_url;
}
Give the get_tiny_url function the URL you want to shorten and it will return the shortened URL using TinyURL's API.
Here's an example of a whole script:
PHP<?php
function get_tiny_url($url) {
$api_url = 'https://tinyurl.com/api-create.php?url=' . $url;
$curl = curl_init();
$timeout = 10;
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $api_url);
$new_url = curl_exec($curl);
curl_close($curl);
return $new_url;
}
$tiny_url = get_tiny_url('https://sabe.io/blog/php-create-tiny-url');
echo $tiny_url;
?>
Here's the output:
BASHhttps://tinyurl.com/yyh5vqnv
Our PHP app calling the TinyURL API
Conclusion
We've created a PHP script that will create a TinyURL from a long URL using TinyURL's API. Hopefully, you can see how easy it is to create a URL shortener using PHP.
Thanks for reading!
Resources
How to Install Node on Windows, macOS and Linux
Getting Started with Express
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
