How to shorten long URLs in a user-input text by using TinyURL programmatically

TinyURL allows long URL to be shortened. In this example, I’d like to show how you can build a text form that contains text keyed in by a user, and sends to the server-side PHP to detect those overly long URLs and shorten them one by one by sending them to TinyURL service.

Before I proceed, I’d like to let you know that TinyURL has an API, which is as follows and it returns a single string only that is the tiny url which has been shortened from the given “url” parameter.

http://tinyurl.com/api-create.php?url=http://myverylongurl.com/this-is-a-very-long-url.html

In this example, I have a very simple web form that allows a user to input some text, and it uses AJAX to submit the input text to a PHP script at the server side when the user is typing the text away (triggered by the onKeyPress event). And the server-side PHP returned result is to be shown in the DIV with id “theresulttext”. The web form is as follows:

<b>Input your text below</b><br/>

<textarea cols=”60″ rows=”5″ style=”border:1px solid #aabbcc;padding:5px;
background:#EEEEF8;color:#990000;”
id=”yourinputtext” onKeyPress=”sendText();”>

</textarea>

<br/>

<b>The result:</b><br/>

<div style=”border:1px solid #aabbcc;padding:5px;
background:#EEEEF8;color:#009900;” id=”theresulttext”>

</div>

The JavaScript function “sendText” which makes an AJAX call to the server-side PHP (shortenurl.php) to shorten all the long
URLs contained in the input text and return back the input text.

function sendText()
{
  var yourinputtext= document.getElementById(‘yourinputtext’);
  var url=’shortenurl.php?txt=’+encodeURIComponent(yourinputtext.value);
  var theresulttext= document.getElementById(“theresulttext”);
  theresulttext.innerHTML=”Please wait….”;

  var req;
  if (window.XMLHttpRequest)
  {
    req = new XMLHttpRequest();
    req.onreadystatechange = showres(req);
    req.open(‘GET’, url, true);
    req.send(null);
  }
  /** branch for IE/Windows ActiveX version **/
  else if (window.ActiveXObject)
  {
    req = new ActiveXObject(‘Microsoft.XMLHTTP’);
    if (req)
    {
      req.onreadystatechange = showres(req);
      req.open(‘GET’, url, true);
      req.send();
    }
  }
}
/**
The call-back function that displays the returned text on the “theresulttext” div
*/
function showres(req)
{
  return function()
  {
    if (req.readyState == 4)
    {
    /** only if “OK” */
      if (req.status == 200)
      {
        var theresulttext= document.getElementById(‘theresulttext’);
        theresulttext.innerHTML=req.responseText;
        
      }
    }
  }
}

The PHP script that takes the submitted text, checks for overly long URLs, shortens them one by one using TinyURL and return
the shortened text.

<?php
/**
Use session to store shortened URLs in an array to avoid
repeatedly sending over for shortening
*/
session_start();
/**
Create a new array, if this is the first time
using the page
*/
if ( !session_is_registered (“shortened_urls”))
  $_SESSION["shortened_urls"]= array();
header(“Content-type:text/plain”);
$txt = $_REQUEST['txt'];
$longurls =checklongurls ($txt);
$shortenurls= shortenurls($longurls);

echo bl2br(replacelongswithshorts($txt, $longurls, $shortenurls));

/**
The PHP function that strips the input text
and uses the regex pattern to extract URLs in the input text
and stores them in an array. Each URL is considered long if it’s exceeded
the allowed length,specified in the $morethanlen paramater, which is 30
by default
*/

function checklongurls($txt,$morethanlen=30)
{
  $a = array();
  $n=0;
  $spltxt=split(” “, $txt);
  for ($i=0; $i < count($spltxt); $i++)
  {

    if ( eregi("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", $spltxt[$i],$aa) )
    {
      $a[$n]= $aa[0];
      $n++;
    }
  }

  $a2= array();
  $n=0;
  for ($r=0; $r< count($a); $r++)
  {
    if ( strlen($a[$r])>=$morethanlen)
    {
      $a2[$n]=$a[$r];
      $n++;
    }
  }

  return $a2;
}


/**
The function to check if the specified long URL has been shortened,
if it’s contained in the sessioned associative array “shortened_urls”
*/

function hasbeenshortened($lurl)
{
  $surl=$_SESSION["shortened_urls"][$lurl];
 return ($surl!=null && trim($surl)!=”);
}


/**
The function takes the array that contains all the long URLs need to be
shortened and sends to tinyURL service to shorten it one by one
and returns an array that has the shortened URls
*/

function shortenurls($a)
{
  $ra=array();
  for ($i=0; $i < count($a); $i++)
  {


    /**
    If it has been shortened before, then no need
    to resend to TinyURL (to save bandwidth and with faster response),
    just take it from the associative array stored in PHP session
    */

    if (hasbeenshortened($a[$i]))
    {
      $ra[$i]=$_SESSION["shortened_urls"][$a[$i]];
    }
    else
    {
      //send to TinyURL for shortening it
      $ra[$i]=sendtotinyurl($a[$i]);

      /**
      Store into associative array in session to cache the shortened URLs
      */

      $_SESSION["shortened_urls"][$a[$i]]= $ra[$i];
    }
  }
  return $ra;
}

/**
The function that uses the tinyURL api and sends the input URL to
obtain and return the shortened URL
*/

function sendtotinyurl($url)
{
  $fh = fopen(“http://tinyurl.com/api-create.php?url=$url”,”r”);
  $txt=”;
  while ($data = fread($fh, 4096))
  {
    $txt.=$data;
  }
  return $txt;
}


/**
The function uses str_replace to replace the input text for each
occurance of the specified long URLs contained
in $lurls array by each shortened URL in the $surl array
*/

function replacelongswithshorts($txt,$lurls, $surls)
{
  for ( $r=0; $r< count($lurls); $r++)
  {
    $txt=str_replace($lurls[$r],"<a
href=\"".$surls[$r]."\" target=_new>".$surls[$r]."</a>", $txt);
  }
  return $txt;
}
?>

You can also try out the working example here or here. FYI, you can also use other URL shortening services besides TinyURL, there are some even provide you with shorter URL due to they have shorter domain names, such as follows:

http://bit.ly/api?url={your_url}

http://is.gd/api.php?longurl={your_url}

Enter your email address to subscribe our newsletter or feed for FREE:

Delivered by FeedBurner


Bookmark with:

[Delicious]    [Digg]    [Reddit]    [Facebook]    [StumbleUpon]

0 Responses to “How to shorten long URLs in a user-input text by using TinyURL programmatically”


  1. No Comments

Leave a Reply

You must login to post a comment.