Twitter is a phenomenal idea. And one can safely assume that the only thing that changed the face of the internet and how we interacted is, Twitter.

Twitter is beautifully made with amazing light weight and fast loading scripts and techniques. Many of us wonder, what exactly powers Twitter and make it so huge that life virtually seems impossible without tweeting.

Well, on the technical side, the power of Twitter lies in their open API format that allows any developer to make a Twitter application, distribute it to world-wide users and have fun!

There is no limitation and definitely, no selection/rejection criteria as it is there for the iPhone infrastructure. If you are good at php, design a Twitter application in it. If you like Java, make one in it. Twitter doesn’t care unless you spam their system by sending zillions of API requests per unit time (they have a limit on that thing).

Well, that was about Twitter’s phenomenal growth. Now what about the native thing? What about the Twitter? How was the real hero made? Well, to tell you the truth, I always wondered how come such a powerful thing came into existence. Was it CSS or Javascript or XML or PHP? But one day, I decided to make my own Twitter (yeah, no kidding). And I combined all the technologies I possibly knew and I was able to make a small prototype of Twitter.

Why Am I writing this tutorial?

First thing first, I was really thrilled when my experiment of making my own Twitter was successful. It wasn’t that great, but it was enough to blow my mind and make me write this tutorial.

Secondly, with this tutorial, you would come to know the real power behind combining the very basic things that you might already have known since the starting days of your web design career. Well, here’s a screenshot of the end result (click to check out the demo).

Creating Your Own Twitter

Let’s Get Started

So, without further ado, let’s get started. The technologies which we would be using to make our own Twitter timelines are:

  • SQL (Stands for Structured Query Language). It’s a database management language. Don’t worry, you don’t have to be a “pro” at it for the time being.
  • XHTML (We’ll be using it for the front end)
  • CSS (For styling purposes)
  • jQuery (For the magical effects!)
  • PHP (Of course, the core of all)

The Database

This is where all your (and the rest of the world’s) tweets will be stored. Each tweet will be stored with a unique id in the database table. We would be using MySQL database, which is an open source architecture and used in ninety percent of the web applications. All you need to do is:

  • Make a blank database in your phpMyAdmin
  • Go to the SQL section and run the following query:
CREATE TABLE `demo_twitter_timeline` ( `id` int(10) NOT NULL auto_increment, `tweet` varchar(140) collate utf8_unicode_ci NOT NULL default '', `dt` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Note: Whatever table name, user name, password you want to use, make sure you update the connect.php file supplied with the demo files of this tutorial. Otherwise, nothing is going to work.

The Front End (XHTML)

This one is going to be easy. We would be combining the properties of CSS and jQuery in our XHTML code. Your index.php file should look like this:

<div id="twitter-container">
<form id="tweetForm" action="submit.php" method="post">
    <span class="counter">140</span>
    <label for="inputField">What are you doing?</label>
    <textarea name="inputField" id="inputField" tabindex="1"rows="2" cols="40"></textarea>
    <input class="submitButton inact" name="submit" type="submit" value="update" />
    <span class="latest"><strong>Latest: </strong><span id="lastTweet"><?=$lastTweet?></span></span>
    <div class="clear"></div>
</form>

<h3 class="timeline">Timeline</h3>
    <ul class="statuses"><?=$timeline?></ul>
</div>

Let me explain a little here.

Our whole framework lies in the div id of “twitter-container”. It literally holds the entire layout within itself and keep the design stable. We have applied some CSS styles to it too.

Next, the text box where we would enter our tweet is contained in the “tweetForm”. It’s an AJAX form id.

Later in the code, we have implied different ids to contain the timestamp and other important things with custom CSS built around them.

The CSS

/* Page styles */

body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{
    margin:0px;
    padding:0px;
}

body{
    margin-top:20px;
    background:#d9f4f7;
}

/* Form & timeline styles */

#twitter-container{
    -moz-border-radius:12px;
    -khtml-border-radius: 12px;
    -webkit-border-radius: 12px;
    border-radius:12px;
    border:6px solid #00d9ff;
    padding:10px;
    width:600px;
    font-size:11px;
    font-family:'Lucida Grande',sans-serif;
    color:#333333;
    margin: 0px auto -1px auto;
}

label{
    font-size:20px;
    display:block;
}

.counter{
    color:#CCCCCC;
    float:right;
    font-family:Georgia,serif;
    font-size:32px;
    font-weight:bold;
    height:40px;
    overflow:hidden;
}

textarea{
    width:594px;
    height:38px;
    margin:5px 0 10px 0;

    border:1px solid #AAAAAA;
    padding: 4px 2px;

    font-family:'Lucida Grande',sans-serif;
    overflow:auto;
    font-size:14px;
}

.clear{
    clear:both;
}

.submitButton{
    color:#666666;
    font-size:14px;
    height:32px;
    width:115px;
    -moz-border-radius:6px;
    -khtml-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius:6px;
    border:1px solid #cccccc;
    background:url(img/button_bg.gif) repeat-x #f5f5f5;
    cursor:pointer;
    float:right;
}

.submitButton:hover{
    background-position:bottom;
    border-color:#dddddd;
    color:#333333;
}

.inact,.inact:hover{
    background:#f5f5f5;
    border:1px solid #eeeeee;
    color:#aaaaaa;
    cursor:auto;
}

.latest{
    color: #666666;
}

ul.statuses{
    margin:10px 0;
}

ul.statuses li {
    position:relative;
    border-bottom:1px dashed #D2DADA;
    padding:15px 15px 15px 10px;
    list-style:none;
    font-size:14px;
}

ul.statuses li:first-child{
    border-top:1px dashed #D2DADA;
}

ul.statuses li:hover {
    background-color:#F7F7F7;
}

h3.timeline{
    margin-top:20px;
    color:#999999;
    font-size:20px;
    font-weight:normal;
}

div.tweetTxt{
    float:left;
    width:498px;
    overflow:hidden;
}

ul.statuses a img.avatar{
    float:left;
    margin-right:10px;
    border:1px solid #446600;
}
div.date{
    line-height:18px;
    font-size:12px;
    color:#999999;
}

li a, li a:visited {
    color:#007bc4;
    text-decoration:none;
    outline:none;
}

li a:hover{
    text-decoration:underline;
}

The CSS code is self-explanatory, but let me explain some important things here too.

On the first block of code, we have reset the page styles that nullify anything that can cause style conflicts.

Next, the code blocks of line 16 to 19 use the latest CSS3 properties that make the corners of our div containers round, giving them a sleek and stylish look. If you have an old browser, the code may not work and you may not see the round edged borders.

Rest of the code is pretty simple with later being the Submit Button, where we have again used the rounded corner CSS 3 technique.

The jQuery Magic

And here comes the magic code that will embed all the working things inside our Twitter prototype and make the User Interface even more interesting.

$(document).ready(function(){
    $('#inputField').bind("blur focus keydown keypress keyup", function(){recount();});
    $('input.submitButton').attr('disabled','disabled');
    $('#tweetForm').submit(function(e){
        tweet();
        e.preventDefault();
    });
});
function recount()
{
    var maxlen=140;
    var current = maxlen-$('#inputField').val().length;
    $('.counter').html(current);
    if(current<0 || current==maxlen)
    {
        $('.counter').css('color','#D40D12');
        $('input.submitButton').attr('disabled','disabled').addClass('inact');
    }
    else
        $('input.submitButton').removeAttr('disabled').removeClass('inact');
    if(current<10)
        $('.counter').css('color','#D40D12');
    else if(current<20)
        $('.counter').css('color','#5C0002');
    else
        $('.counter').css('color','#cccccc');
}
function tweet()
{
    var submitData = $('#tweetForm').serialize();
    $('.counter').html('<img style="padding:12px" src="img/ajax_load.gif" alt="loading" width="16" height="16" />');
    $.ajax({
        type: "POST",
        url: "submit.php",
        data: submitData,
        dataType: "html",
        success: function(msg){
            if(parseInt(msg)!=0)
            {
                $('ul.statuses li:first-child').before(msg);
                $("ul.statuses:empty").append(msg);
                $('#lastTweet').html($('#inputField').val());
                $('#inputField').val('');
                recount();
            }
        }
    });
}

The PHP

Our php code will act as a bridge between the user interface and the database and probably is the most important part of our prototype. The php code inserts the user data into the MySQL database tables.

Here’s the code for submit.php:

define('INCLUDE_CHECK',1);
require "functions.php";
require "connect.php";

if(ini_get('magic_quotes_gpc'))
$_POST['inputField']=stripslashes($_POST['inputField']);

$_POST['inputField'] = mysql_real_escape_string(strip_tags($_POST['inputField']),$link);

if(mb_strlen($_POST['inputField']) < 1 || mb_strlen($_POST['inputField'])>140)
die("0");

mysql_query("INSERT INTO demo_twitter_timeline SET tweet='".$_POST['inputField']."',dt=NOW()");

if(mysql_affected_rows($link)!=1)
die("0");

echo formatTweet($_POST['inputField'],time());

Explanation: First of all, we checked the state of magic_quotes_gpc. It is enabled by default on some web hosts and its function is to escape all the incoming data automatically. So, it that remains enabled, we would not be able to enter any data in your stream. So, we first check it’s state. Secondly, We escape the data, do a check of the length of $_POST[‘inputField’] and insert the row in our database. We echo a formatted tweet using formatTweet (more on that in a minute), that is returned to the tweet() jQuery function as the variable msg.

function.php:

<?php
if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');
function relativeTime($dt,$precision=2)
{
    $times=array(   365*24*60*60    => "year",
                    30*24*60*60     => "month",
                    7*24*60*60      => "week",
                    24*60*60        => "day",
                    60*60           => "hour",
                    60              => "minute",
                    1               => "second");

    $passed=time()-$dt;
    if($passed<5)
    {
        $output='less than 5 seconds ago';
    }
    else
    {
        $output=array();
        $exit=0;

        foreach($times as $period=>$name)
        {
            if($exit>=$precision || ($exit>0 && $period<60)) break;

            $result = floor($passed/$period);
            if($result>0)
            {
                $output[]=$result.' '.$name.($result==1?'':'s');
                $passed-=$result*$period;
                $exit++;
            }
            else if($exit>0) $exit++;
        }

        $output=implode(' and ',$output).' ago';
    }

    return $output;
}
function formatTweet($tweet,$dt)
{
    if(is_string($dt)) $dt=strtotime($dt);

    $tweet=htmlspecialchars(stripslashes($tweet));

    return'
    <li>
    <a href="#"><img class="avatar" src="img/avatar.jpg" width="48" height="48" alt="avatar" /></a>
    <div class="tweetTxt">
    <strong><a href="#">My_Own_Twitter</a></strong> '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s"\']+)/i','<a href="$1" rel="nofollow" target="blank">$1</a>',$tweet).'
    <div class="date">'.relativeTime($dt).'</div>
    </div>
    <div class="clear"></div>
    </li>';
}
?>

Here, we have used a relative time array, that displays the tweet format in a relative way, rather than an absolute way. In more simple terms, it would display “10 minutes earlier” rather than “at 8:00 pm”, which is what exactly happens over Twitter.

In the second function, we have used all the other important things including a default user Avatar, which can be changed as per your convenience.

That’s it. If you have done all the above steps correct, you should have a small prototype of your own Twitter ready and up in a jiffy!

You can also download a zip that contains all demo files →
(downloaded 90 times already!)

PS: I’ve used the official Twitter logo which is freely available for download in both png and vector format.

Conclusion

This isn’t a fully functional prototype of Twitter. It’s just a basic model which demonstrate how things really work. With this tutorial we learnt how a much powerful web application could be developed using the things that we already know.

Moreover, you are free to use your imagination and turn it around in any direction to come out with something unique! Do share your shouts below in the comment section. Good Luck 😉

Via http://spyrestudios.com/how-to-create-your-own-twitter-prototype-with-sql-php-and-jquery/

Related Posts with Thumbnails
Tagged with:  

Comments are closed.

WordPress Themes