Sunday, January 20, 2013

How to Connect in Twitter API Using PHP

Connecting to twitter is very tiring because you have to make all the strings required by the twitter API correct. So lets start

First you need to do it to create an application in https://dev.twitter.com and fill the requirements there. Once finished you will have your $consumerKey and $consumerSecret.
I have declared a session start here so that we can just get our tokens directly once we obtain it.

 <?php   
 session_start();  
   $host = "https://api.twitter.com/oauth/request_token";  
   $consumerKey = "h0YUvJVE6AdYBsBLxhL7Nw";  
   $consumerSecret = "AYS7EcrqzcjambZIHsZtXZxOGn0VfJRgYJrqI5aqQ0&";  
   $nonce = time();  
   $timestamp = time();  
   $oauth_signature_method = "HMAC-SHA1";  
   $callback = "";  

All of these variable are self-explanatory since it is all the variables needed by the Twitter API. Note that you should set your $callback in your twitter application.
First, we should obtain the $signature_base_string. In the first $signature_base_string that we will create it using the variables above.

$signature_base_string = "POST&". rawurlencode($host).'&'  
               .rawurlencode("oauth_callback=").rawurlencode($callback)  
               .rawurlencode("&oauth_consumer_key=". ($consumerKey))  
               .rawurlencode("&oauth_nonce=". rawurlencode($nonce))  
               .rawurlencode("&oauth_signature_method=".$oauth_signature_method)  
               .rawurlencode("&oauth_timestamp=".$timestamp)  
               .rawurlencode("&oauth_version=1.1");  
First thing you should note is that strings that will be put in the $signature_base_string should be URL Encoded. This is a dummy $signature_base_string because we still don't have the $oauth_signature.
The $signature_base_string would look something like this:

 POST&https%253A%252F%252Fapi.twitter.com%252Foauth%252Frequest_token%26oauth_consumer_key%3Dh0YUvJVE6AdYBsBLxhL7Nw%2Coauth_nonce%3D1358732765%2Coauth_signature_method%3DHMAC-SHA1%2Coauth_timestamp%3D1358732765%2Coauth_version%3D1.1%2Coatuh_signature%3DuV%2FogNLV%2FwS%2FVYNpdxbxtF5TJro%3D  

Since we have now created our $signature_base_string, we can now make our $oauth_signature. (If you want to clarify things on what these variables represents, you should read a bit in https://dev.twitter.com/docs/auth/creating-signature).

 $oauth_signature = base64_encode(hash_hmac('sha1', $signature_base_string, $consumerSecret,true));  

The signature is calculated by passing the signature base string and signing key to the HMAC-SHA1 hashing algorithm. The details of the algorithm are explained in depth here, but thankfully there are implementations of HMAC-SHA1 available for every popular language. For example, PHP has the hash_hmac function (https://dev.twitter.com/docs/auth/creating-signature).

 We will now write our HTTP header that will be used in our cUrl method.

   $r = "Authorization: OAuth ".'oauth_callback="'.$callback.'"'  
                 .', oauth_consumer_key="'. rawurlencode($consumerKey)  
                 .'", oauth_nonce="'. rawurlencode($nonce)  
                 .'", oauth_signature_method="'.$oauth_signature_method  
                 .'", oauth_timestamp="'.$timestamp  
                 .'", oauth_version="1.1'  
                 .'", oauth_signature="'.rawurlencode($oauth_signature).'"';  
  $r = array($r,'Expect:');  

We will now use cUrl with the settings that we wanted and call the cUrl method.

  $options = array(CURLOPT_HTTPHEADER=>$r,  
            CURLOPT_HEADER=>false,  
            CURLOPT_URL=>$host,  
            CURLOPT_POST=>true,  
            CURLOPT_POSTFIELDS => "",  
            CURLOPT_RETURNTRANSFER=>true,  
            CURLOPT_SSL_VERIFYPEER=>false);  
   $ch = curl_init();  
   curl_setopt_array($ch, $options);  
   $response= curl_exec($ch);  

After executing this, our $response will contain the oauth_token and the oauth_token_secret. We can save it in our session that it can be used in later transactions.

  $response_array = explode('&', $response);  
   $_SESSION['oauth_token'] = $response_array[0];  
   $_SESSION['oauth_token_secret'] = $response_array[1];  

Once we obtain our tokens needed, we can now redirect to our page to the twitter to authenticate us.
  header("Location: https://api.twitter.com/oauth/authenticate?".$response_array[0]);  

Here is the full source code:

 <?php    
   session_start();  
   $host = "https://api.twitter.com/oauth/request_token";  
   $consumerKey = "h0YUvJVE6AdYBsBLxhL7Nw";  
   $consumerSecret = "AYS7EcrqzcjambZIHsZtXZxOGn0VfJRgYJrqI5aqQ0&";  
   $nonce = time();  
   $timestamp = time();  
   $oauth_signature_method = "HMAC-SHA1";  
   $callback= "";+  
   $signature_base_string = "POST&". rawurlencode($host).'&'  
               .rawurlencode("oauth_callback=").rawurlencode($callback)  
               .rawurlencode("&oauth_consumer_key=". ($consumerKey))  
               .rawurlencode("&oauth_nonce=". rawurlencode($nonce))  
               .rawurlencode("&oauth_signature_method=".$oauth_signature_method)  
               .rawurlencode("&oauth_timestamp=".$timestamp)  
               .rawurlencode("&oauth_version=1.1");  
   $oauth_signature = base64_encode(hash_hmac('sha1', $signature_base_string, $consumerSecret,true));  
   $r = "Authorization: OAuth ".'oauth_callback="'.$callback.'"'  
                 .', oauth_consumer_key="'. rawurlencode($consumerKey)  
                 .'", oauth_nonce="'. rawurlencode($nonce)  
                 .'", oauth_signature_method="'.$oauth_signature_method  
                 .'", oauth_timestamp="'.$timestamp  
                 .'", oauth_version="1.1'  
                 .'", oauth_signature="'.rawurlencode($oauth_signature).'"';  
   $r = array($r,'Expect:');  
   $options = array(CURLOPT_HTTPHEADER=>$r,  
            CURLOPT_HEADER=>false,  
            CURLOPT_URL=>$host,  
            CURLOPT_POST=>true,  
            CURLOPT_POSTFIELDS => "",  
            CURLOPT_RETURNTRANSFER=>true,  
            CURLOPT_SSL_VERIFYPEER=>false);  
   $ch = curl_init();  
   curl_setopt_array($ch, $options);  
   $response= curl_exec($ch);  
   $response_array = explode('&', $response);  
   $_SESSION['oauth_token'] = $response_array[0];  
   $_SESSION['oauth_token_secret'] = $response_array[1];  
  header("Location: https://api.twitter.com/oauth/authenticate?".$response_array[0]);  
 ?>  

In my next post, I will show how to create a post status request in twitter.



Monday, October 1, 2012

Media Nowadays


Media has been the part of the people's lives. It may be on the television, on radio or in many other devices that concerning about media. But how does the media influenced our lives? For me, media did gave me a lot of information that I needed for me to learn. Media gave me shows where I can laugh and relax for some time. It fulfilled my needs for the hunger of entertainment. When it comes to the mass media news, my dilemma arises. The media news can easily manipulate information to make the people think the other way around. They either gives us the beautiful lies or the ugly truth. Media in terms of entertainment is where I appreciate much than media news.

Wednesday, August 15, 2012

A Place Where Every People Must See


A place where every people has this unique personality of always smiling and always easy to approach, who wouldn’t want to stay that kind of place?
                A place surrounded by gigantic mountains and attached by the vast sea. With this kind of city, it would be impossible for the people not to utilize the gift of nature. Fortunately, Iligan City possesses this one of a kind beauty that all Iliganons are proud of.
                In speaking of tourist spots Iligan, there would be countless spots but I just want to enumerate somethings.
                One known tourist spot in Iligan is the bizarre length of of Maria Cristina falls which is labeled as the Philippines longest waterfall. With a glance of it, you will be mesmerized with one of the wonders of nature. A wonder that was preserved and instead of just used for the eye pleasure, it was utilized to power up turbines to lighten up the city.
                In terms of pools, Timoga is just one the many place in Iligan can represent to. With the water so cold, it would be a perfect get-away from the summer. If you want a place in the pool with your kids, kiddie pool in Timoga would be the most suitable place for them. An accommodation for the children wherein you can always be sure that they will always be safe. If you want to go for a dive, there will always a place for you with a diving board with a height which can enable you to make different diving stances.

                Would you still be up for the weekend? Well, Iligan will always be there you. The night market will be there for you in the public plaza during weekends. If you don’t have the enough penny, ukay-ukay in the night market is always there. Even the prices are cheap, quality will always be there. Street foods like kwek-kwek, balot, etc. are what you want? There will always a place for that in the market and you wouldn’t need to budget your money because the foods are just so cheap and are just enough to surely grant your satisfaction.

                 If you just want a place savor the beauty of nature, you can just go to the city hall located in Pala-o and you can see a place with a wonderful view of the Iligan city. You can see from the above the explicit beauty of Iligan city has to offer. It’s just not top view of the city you can see in the city hall that is unique, it’s also on that place that it was built is also unique because of the landscape is going up which will be a perfect spot for jogging exercise during the early morning. It’s not just that, children are also perfectly suitable in the city hall as there are places that are specially made for them.  
                These are just one of the few reasons why you should go to Iligan, there are plenty more. So don’t hesitate to choose Iligan for a vacation because Iligan has many things to offer! 


An official entry to the Iligan BLogging Contest 2012

                

Monday, August 13, 2012

#7 The Lorax



"UNLESS someone like you cares a whole awful lot, nothing is going to get better. It’s not." - Dr.Seuss

    Development of the humanity comes with a great price.  As we people approach the new era, the era of the machines Mother Nature is now just left in the corner, left unaided in the darkness. In the movie “The Lorax”, it relates to what is happening in the modern times.
                There was a boy named Ted who was eager to find a genuine tree to impress this lassie girl of his dreams since at that time, things are made mostly by plastics. His pursuit in finding a tree just to amaze his crush turned out to be a bigger quest as this was the reason for the society to open their eyes and grasp the unpleasant truth that was concealed to them for a long time.
                As Ted goes out in the village called “Thneed-Ville”, he met a guy called the “Onceler”. The Onceler told everything to Ted why every trees ceased to exist anymore.
                The Onceler was this man who was so determined that his research will be a huge success. His research was to invent an all-purpose cloth however, in order to yield such cloth, the leaves of a Truffula tree is necessary.  As soon as the Onceler cut down the glooming Truffula tree, the guardian of the nature, known as the “Lorax”, came out to voice out for the trees. The research of the Oncler came to be a really big hit that made him a prosperous man.  He needed to cut more trees to create more of his product but little did he know that trees were ceasing to exist any longer.  As the last tree was cut down, the Lorax can’t do anything. Instead, he just left a word “unless” carved in a rock.

                The Onceler entrusted Ted to plant the last seed of the Truffula tree to restore the balance in the world. Of course, the government of Thneed-Ville, Aloysius O'Hare, didn’t agree with Ted to plant the seed as this could the reason for his business to fall down. But Ted used the power of the society as he let the people show the wasteland around their pleasing city. In the end, Ted was able to plant the last seed and restored the true beauty of nature.


Monday, July 30, 2012

#5 My Thoughts


In the word they call “peace”, how much can you sacrifice to achieve it? The peace can easily be said but difficult to do. What would you give in? Happiness for you own or sacrifice something from yourself for the good of others?
                Ming-ming, the drama that I watched depicts on how the early generation of Muslims that settled here in the Philippines on managing peace between tribe. Redo is a common thing back in the days and their clan has a redo with another clan. Redo is committing revenge to a family or clan. The saying “an eye for an eye” relates to it. In the drama Ming-ming, Aye, as I remembered their names, was chosen in their clan to have an arranged marriage to another man of their rival clan to preserve peace between clan. But Aye didn’t want the man engaged to her because she described him as “a man with distorted face”. For a month, Aye was sent somewhere in Luzon to study there but that opportunity of studying there for knowledge was not been followed. She was just wasting time and money. She committed a relationship that wasn’t for her. Every person in this world has the right to make their own decision. Making the best judgment out of all the choices but then, this was not the situation in the past. The decision of the elders will always be followed and respected. For all these decision can benefit the entire clan. It could gain glory and prosperity for both clans if there is an agreement between the two. Like in the case of Aye, she will be married to another man, not only for the benefit of peace but with the wealth. After Ar and Pi knew what Aye was doing while being sent away to study, Aye was demanded to go home to their province and stay there. Yet it was too late for them to take the action because Aye was already committed a sin, a child was already developing in her womb. Aye was pregnant but with a wrong father. In order to prevent in a war that might wage, Ar and Pi hid it as a secret and make everyone believes that the father of Aye’s child is of the other clans’ man. However, Aye would still prefer being with the true father of her child than with the other man that she was been arranged to marry. She thought selfishly that she didn’t consider in her actions the consequences that might arose. Many people have this trait, always rushing decisions that thinking is not a part of the process anymore and only considering the advantages can bring to him. Time have past and the identity of Aye’s child named Ming-Ming was been discovered. Things have been revealed. Ming-ming was sent away from her mother and imprisoned. Ming-ming being felt that she was all alone, committed a suicide.
In the decisions we make in our life, there will always be a corresponding reaction to it. We must take responsibility of our actions and make a stand of it.

Sunday, July 22, 2012

#4 Gratifying Experience







It was my 2nd year of stay in my high school at Philippine Science High School- Central Mindanao Campus when one of the subjects that I needed to tackle was computer programming. Of course at first, I didn’t know a single thing about programming. I was absolutely empty minded on what to do. After a few lectures of that subject, I did felt that I was really into programming. All I needed to do was to read in advance to gain more information about it. Well, I did literally read a book or two cover to cover just to have knowledge on how programming really works. After I finished reading it, my mind started to tack ideas from the book like from simple “Begin and end statements” to “recursive functions” and so on. Well, my teacher didn't expect me to learn those many kinds of idea in just a short period of time. He did applauded me for the excellent performance that I was giving him in the field that he was teaching us.
                The performance that I had been showing off gave me an opportunity to join in computer programming contests. Well, that was too much for me to handle because I would be one of the contestant that will bring the name of ourschool along with my teammate Danica. There was an event held in IIT called ICCF (Iligan City Computing Fair, I’m not really sure if that is what ICCF stands for). One category for the contests of the said event was computer programming. A week before the contest, me and my teammate did a lot of practicing in solving programming problems. Of course at that time, we were so confident that we will win the trophy. But a few moments before the contest, we were informed that college students our opponents would be college students. That lowered my confidence in winning because at that time, I was still in 3rd year high school and I was competing with college students already who  have more knowledge about programming than I do. When the competition started, my hands were shaking because of I was really nervous. I can’t even concentrate on what to do and how to manage my time properly in answering programming problems. In short, I was devastated at that time. At the end of the competition, my adviser was really disappointed for my performance but quitting didn’t occur into my mind. I swore to my adviser and to myself that I will win the next competition that I will be joining.
                Few months later, my adviser told me again that there would be another contest that I would be joining that would be held in Davao City. The moment I received the news, I did practice harder in solving programming problems from dawn to evening, That was how so disparate I was to win the contest. While traveling, I questioned myself, what if I still can’t win this time? If I will lose again, this will just prove of how a failure I am. Still, my confidence didn’t go off that I would not return empty handed. So during the contest, a set of programming problems were given to us. As I opened one by one the papers being handed to us, things rushed into my mind on what kind of problems would come out  and how difficult the problems could be(by the way, my opponents this time are high school students). As I read the problem, I knew that I can solve this things right away because I have already encountered similar problems like this. As a matter of fact, I was the first one to finish solving the problems. While other students were still solving, I just played minesweeper and solitaire on the computer in from of them just to pressure them. That was how confident I was that I would win that time. At the end of the competition, winners were announced and as I hoped that I will win first place, I didn't. But as the second placer was announced my name echoed. I really don’t know what didn’t went right in solving those problems. Still, I was happy because I did win in that said competition. Well that same thing still happened on the national level of the said event. Being so confident yet clumsy, I just ranked 3rd place. Lol.

Sunday, July 15, 2012

#3 Sweet Unforgettable Day Reaction




The story is about a woman who truly misses her mom and even though years have already passed since the death of her mother, she can still feel the emptiness and depression after their lost.Well, who wouldn't feel that same way that the one who was responsible on giving birth of us and the one who cared very much for us would go away? Each and everyone of us would feel that sad emotion deep inside us. It was not only her but all the other members of the family felt the same way. They missed the light of their home and the woman  who cared for all of them. As a child, we should cherish our loved ones because we wouldn't know when will the time int which they cannot be with us anymore. The best thing that we could just do is  to make every moment special and  cherish the love that is being shared to us. 

Then there comes this day where there was a  wedding which was held in their house and while finishing the decorations and arrangement for the wedding, there was this scent in the room that passed through their nostrils and suddenly they remembered someone. It was the very scent that their mother was using. The recalling of their mom just by a scent tells that they really misses the presence of their deceased mother. They wouldn’t leave the room because they really want to be with their mom even though it was only the scent of their mother which remained. They cherished it very much and imagined that she was there with them. They remembered the times that she was still alive and to make every moment special but all they could do was to mourn about the death of their mother.
As the wedding started the scent vanished slowly. Even though it was only a moment that they did feel the presence of their mom, they still made it unforgettable.