PHP Function To Get TinyURL
Published by philipnorton42 on Fri, 06/05/2009 - 11:02TinyURL is a service where you can convert a long URL string to a really small one. For instance, the following URL, which points to the Googleplex on Google Maps.
http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=googleplex&sll=37.579413,-95.712891&sspn=34.512672,45.615234&ie=UTF8&cd=1&z=16
Can be converted to the following.
http://tinyurl.com/qpkor2
This is perfect for posting to Twitter or similar microblogging platforms as it saves lots of character space.
Luckily, TinyURL provides an API, so automatically generating URLs for your application is quite easy. The following functions both do the same thing, return a converted URL, but the first uses file_get_contents() and the second uses fopen() and fread(). Which one you use is up to you. The both also prepare the URL before sending it off to TinyURL so they the URL doesn't break when users try and click on it.
1 2 3 4 | function tinyUrl($url){ $tiny = 'http://tinyurl.com/api-create.php?url='; return file_get_contents($tiny.urlencode(trim($url))); } |
Note that the API returns a 25byte string, so getting the first 26 bytes will cover future changes in case TinyUrl increase the number of characters returned in the future.
Comments
Also, this is a handy
Jamie Bicknell (not verified) - Fri, 06/05/2009 - 13:56@Jamie - Thanks! I was going
philipnorton42 - Fri, 06/05/2009 - 14:14Thanks a lot - your answer
Lele (not verified) - Thu, 04/14/2011 - 12:19Thanks a lot - your answer solved all my problems after several days struggling.
Add new comment