Twittando pelo PHP

Hoje em dia o Twitter está em todos os lugares e sites… E em breve vai ser lançada uma regra que diga que “todo site/portal da web 2.0 deve ter integração com o Twitter“.

Vim aqui mostrar pra vocês como é ridiculamente simples criar um Tweet via PHP sem usar nenhuma classe complicada ou API… Você vai usar apenas a função file_get_contents() do PHP.

Veja o código da função criada para isso:

 
<?php
function tweet($mensagem, $usuario, $senha) {
$contexto = stream_context_create(array(
'http' => array(
'method'  => 'POST',
'header'  => sprintf("Authorization: Basic %s\r\n", base64_encode($usuario.':'.$senha)).
"Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query(array('status' => $mensagem)),
'timeout' => 10
),
));
$ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $contexto);

return (false !== $ret);
}
?>
Viu como a função é simples? Para usá-la é só fazer assim:
 
<?php
$usuario = 'SEU_USUARIO';
$senha = 'SUA_SENHA';
// Cria o tweet
tweet('Testando a função', $usuario, $senha);
?>

 

Se você quiser, pode fazer o download do arquivo (.txt) com a função pronta para uso.

Em alguns servidores WEB a função file_get_contents não permite que você acesse endereços/sites/arquivos externos (usando http e etc)… E, geralmente, nesses servidores existe a biblioteca cURL ativada, então existe também uma versão cURL da função:

 
<?php
function tweet($mensagem, $usuario, $senha)
{
$url = 'http://twitter.com/statuses/update.json';
$fld = http_build_query(array('status' => $mensagem));
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $usuario.':'.$senha);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fld);

$ret = curl_exec($ch);

return false !== $ret;
}
?>

Fonte: ThiagoBelem

NOTICIAS RELACIONADAS:

  1. Bloqueando visitantes pelo IP com MySQL e PHP
  2. Como instalar PHP, MySQL, PHPMyAdmin e FTP no Ubuntu
  3. Funções para tratamento de Arrays
  4. Sistema de votação online em PHP e MySQL
  5. Criando um portal de notícias com área administrativa em PHP com MySQL

Deixe seu comentário, compartilhe sua opinião

Spam Protection by WP-SpamFree

Parceiros:|BRA Concursos |Mural da Vila |Noticias de Urucui |Anita Mulher