Freelance Web Developer

Say Hi

Feb 23, 2010

Update twitter status with php - NOcURL

One of the reasons Twitter is so popular, is its API that allows you to do anything. Here’s how you can tweet without using cURL with PHP.
We have two options-

With stream context

Php function stream_context_create has the magic. It creates and returns a stream context with any options passed.

$username 'username';
$message='YOUR NEW STATUS';
function tweet($message$username$password)
  $context stream_context_create(array(
    'http' => array(
      'method'  => 'POST',
      'header'  => sprintf("Authorization: Basic %s\r\n"base64_encode($username.':'.$password)).
                   "Content-type: application/x-www-form-urlencoded\r\n",
      'content' => http_build_query(array('status' => $message)),
      'timeout' => 5,
  $ret file_get_contents(''false$context); 
  return false !== $ret;
echo tweet($message$username$password);

With socket programing

PHP has a very capable socket programming API. These socket functions include almost everything you need for socket-based client-server communication over TCP/IP. fsockopen opens Internet or Unix domain socket connection.



$message='YOUR NEW STATUS';

$out="POST HTTP/1.1\r\n"
."Authorization: Basic ".base64_encode ("$username:$password")."\r\n"
."Content-type: application/x-www-form-urlencoded\r\n"
."Content-length: ".strlen ("status=$message")."\r\n"
."Connection: Close\r\n\r\n"

$fp fsockopen (''80);
fwrite ($fp$out);
fclose ($fp); 

Labels: ,

By :