user2699508
user2699508

Reputation: 63

How to create bitly shortened url from user's inputed text?

Begginer here, people. Could anybody suggest any kind of solution? I've an user inputed text. First of all I check if the text has any urls:

 $post = preg_replace('/https?:\/\/[\w\-\.!~?&+\*\'"(),\/]+/','<a class="post_link"          
 href="$0">$0</a>',$post);

And after that I need to retrieve that url and put as a variable($url) to this function:

 $short=make_bitly_url('$url','o_6sgltp5sq4as','R_f5212f1asdads1cee780eed00d2f1bd2fd794f','xml');

And finally, echo both url and user's text. Thanks in advance for ideas and critiques.

I've tried something like that:

 $post = preg_replace('/https?:\/\/[\w\-\.!~?&+\*\'"(),\/]+/e',$url,$post){
 $shorten = make_bitly_url($url,'o_6sgltpmm5sq4','R_f5212f11cee780ekked00d2f1bd2fd794f','json');
 return '<a class="post_link" href="$shorten">$shorten</a>';
 };

But even for me it looks some kind of nonsense.

Upvotes: 1

Views: 503

Answers (2)

cssyphus
cssyphus

Reputation: 40038

Here's how to use the bit.ly API from PHP:

/* make a URL small */
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
    //create the URL
    $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

    //get the url
    //could also use cURL here
    $response = file_get_contents($bitly);

    //parse depending on desired format
    if(strtolower($format) == 'json')
    {
        $json = @json_decode($response,true);
        return $json['results'][$url]['shortUrl'];
    }
    else //xml
    {
        $xml = simplexml_load_string($response);
        return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
    }
}

/* usage */
$short = make_bitly_url('http://davidwalsh.name','davidwalshblog','R_96acc320c5c423e4f5192e006ff24980','json');
echo 'The short URL is:  '.$short; 

// returns:  http://bit.ly/11Owun

Source: David Walsh article


HOWEVER, if you wanted to create your own URL shortening system (similar to bit.ly -- and surprisingly easy to do), here is an 8-part tutorial from PHPacademy on how to do that:

Difficulty level: beginner / intermediate

Each video is approx ten minutes.

Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Part 7 Part 8

Upvotes: 1

Izodn
Izodn

Reputation: 152

Bitly does have an API available for use. You should check out API Documentation

Upvotes: 1

Related Questions