12.3. "Post to Twitter" Link

Your next task is just for fun: it adds a "Post to Twitter" link to the bottom of each blog entry. When clicked, this link takes a user to her Twitter[] home page and fills out her status field automatically with the title of the blog and a URL.

[] http://twitter.com

You use a shortened URL here because Twitter has a 140 character limit for status updates, and blog URLs have a tendency to be fairly long. To shorten your blog's URLs, you use the shortening service, http://bit.ly.

NOTE

Twitter is a social networking site that pioneered the concept of "micro-blogging," or status updates limited to 140 characters. As I write this, Twitter is one of the most popular and fastest-growing services on the web.

12.3.1. Creating a Shortened Link with http://bit.ly

The first step for creating a "Post to Twitter" link is to take advantage of the bit.ly API.[] An API, or application programming interface, gives programmers a way to access a software tool or library.

[] http://en.wikipedia.org/wiki/API

In the case of bit.ly, the API defines a request string format that returns a response. The request string is the URL you want to shorten, as well as other information including the bit.ly version, log-in name, API key (an authorization code), and a response format.

You access the bit.ly API by creating a new function in functions.inc.php that you call shortenUrl(). This function accepts the URL you want to shorten as an argument.

When you create shortenUrl(), begin by building the request you want to send to the bit.ly API. Send your requests for URL shortening to http://api.bit.ly/shorten, along with a query string that contains all the information discussed so far—a log-in name, API key, and so on.

In functions.inc.php, create the function shortenUrl() and build the API request by inserting the cold in bold:

function shortenUrl($url)
{
    // Format a call to the bit.ly API
    $api = 'http://api.bit.ly/shorten';
    $param = 'version=2.0.1&longUrl='.urlencode($url).'&login=phpfab'
        . '&apiKey=R_7473a7c43c68a73ae08b68ef8e16388e&format=xml';
}

The values passed for login and apiKey should be swapped out for your own bit.ly account credentials. You can obtain these for free by setting up an account at http://bit.ly.


Your next step is to send the request to bit.ly and load the response into memory. To do this, your script needs to connect to bit.ly remotely, which you can accomplish using the file_get_contents() function, which opens, reads, and returns the content of a file. By supplying the bit.ly API command to the function, you end up loading the response from the API into a variable.

Next, add the following code in bold to shortenUrl() to open a connection to the bit.ly API and load the response:

function shortenUrl($url)
{
    // Format a call to the bit.ly API
    $api = 'http://api.bit.ly/shorten';
    $param = 'version=2.0.1&longUrl='.urlencode($url).'&login=phpfab'
        . '&apiKey=R_7473a7c43c68a73ae08b68ef8e16388e&format=xml';

    // Open a connection and load the response
    $uri = $api . "?" . $param;

    $response = file_get_contents($uri);
}

The last step: Separate the shortened URL from the response. The requested format was XML, so the script needs a way to access the nodes within the XML response.

For example, you get this response you shorten the URL, http://google.com:

<bitly>
    <errorCode>0</errorCode>
    <errorMessage></errorMessage>
    <results>
        <nodeKeyVal>
            <userHash>11etr</userHash>
            <shortKeywordUrl></shortKeywordUrl>
            <hash>3j4ir4</hash>
            <nodeKey><![CDATA[http://google.com]]></nodeKey>
            <shortUrl>http://bit.ly/11etr</shortUrl>
        </nodeKeyVal>
    </results>
    <statusCode>OK</statusCode>
</bitly>

Each nested level of XML is essentially a container. This means that the whole response is in a container called bitly. You can find the results container inside the bitly container, which itself contains the nodeKeyVal container. nodeKeyVal contains shortUrl, which contains the shortened URL. This means that accessing the shortened URL from outside the XML requires that you access bitly, results, nodeKeyVal, and finally shortUrl.

Since PHP 5, developers have been able to use a library called SimpleXML, which makes it easy to traverse XML nodes. To extract the shortened URL from the XML response, you need to create an XML object using simplexml_load_string() and store it in the $bitly variable. Once you do this, you can drill down within the XML easily.

Add the code in bold to shortenUrl() to extract and return the shortened URL from the loaded response:

function shortenUrl($url)
{
    // Format a call to the bit.ly API
    $api = 'http://api.bit.ly/shorten';
    $param = 'version=2.0.1&longUrl='.urlencode($url).'&login=phpfab'
        . '&apiKey=R_7473a7c43c68a73ae08b68ef8e16388e&format=xml';

    // Open a connection and load the response
    $uri = $api . "?" . $param;
    $response = file_get_contents($uri);

    // Parse the output and return the shortened URL
    $bitly = simplexml_load_string($response);
    return $bitly->results->nodeKeyVal->shortUrl;
}

Now you can shorten any URL by passing it to this function, which returns the URL for use elsewhere in your scripts.

NOTE

bit.ly always returns the same short URL for a given web address, so it's perfectly acceptable to save the returned short URL in the database. Additionally, bit.ly provides a JavaScript API that lowers the impact on bit.ly's service and eliminates a server request from your script.

12.3.2. Generating an Automatic Status Update for Twitter

With shortened URLs just a function call away, you're ready to generate the "Post to Twitter" link at the bottom of each blog. You generate this link from another function, which you name postToTwitter(). This function accepts the title of the entry as its only argument.

This function uses values from the $_SERVER superglobal to determine the current entry's URL, then shortens it. It then appends the shortened URL to the entry title, URL encodes the whole string using urlencode(), and adds a link to Twitter as the value of the status variable.

The Twitter link points to http://twitter.com/?status=, which takes any logged in Twitter user to his homepage and fills his status box with the contents of the status variable in the query string.

In functions.inc.php, write the postToTwitter() function by adding the code in bold:

function postToTwitter($title)
{
    $full = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $short = shortenUrl($full);
    $status = $title . ' ' . $short;
    return 'http://twitter.com/?status='.urlencode($status);
}

12.3.2.1. Displaying the Link on Entries

The last thing you need to do is insert the generated link into the entry display. Do this by modifying index.php. Only fully displayed blog entries should have "Post to Twitter" links, so add a call to postToTwitter() only inside the conditional block that checks whether $fulldisp is set to 1.

Inside the block, add a call to postToTwitter() if the current page is the blog and store the return value in $twitter. If the user is on the about page, set the $twitter variable to NULL.

Then, simply insert the $twitter variable into the HTML output to add the link:

// If the full display flag is set, show the entry
if($fulldisp==1)
{

    // Get the URL if one wasn't passed
    $url = (isset($url)) ? $url : $e['url'];

    if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 1)
    {
        // Build the admin links
        $admin = adminLinks($page, $url);
    }
    else
    {
        $admin = array('edit'=>NULL, 'delete'=>NULL);
    }

// Format the image if one exists
    $img = formatImage($e['image'], $e['title']);

    if($page=='blog')
    {
        // Load the comment object
        include_once 'inc/comments.inc.php';
        $comments = new Comments();
        $comment_disp = $comments->showComments($e['id']);
        $comment_form = $comments->showCommentForm($e['id']);

        // Generate a Post to Twitter link
        $twitter = postToTwitter($e['title']);
    }
    else
    {
        $comment_form = NULL;
        $twitter = NULL;
    }

?>

        <h2> <?php echo $e['title'] ?> </h2>
        <p> <?php echo $img, $e['entry'] ?> </p>
        <p>
            <?php echo $admin['edit'] ?>
            <?php if($page=='blog') echo $admin['delete'] ?>
        </p>
        <?php if($page=='blog'): ?>
        <p class="backlink">
            <a href="<?php echo $twitter ?>">Post to Twitter</a><br />
            <a href="./">Back to Latest Entries</a>
        </p>
        <h3> Comments for This Entry </h3>
        <?php echo $comment_disp, $comment_form; endif; ?>

<?php

} // End the if statement

To see this in action, load an entry in your browser (see Figure 12-4).

Figure 12.4. The "Post to Twitter" link on fully displayed blog entries

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.123.73