├── .gitignore ├── TwitterAPIExchange.php ├── enviarTweet.php ├── hacerFav.php ├── hacerFollow.php ├── hacerRT.php ├── hacerUnfollow.php ├── insertarBD.php ├── nbproject ├── project.properties └── project.xml └── searchTweets.php /.gitignore: -------------------------------------------------------------------------------- 1 | /nbproject/private/ -------------------------------------------------------------------------------- /TwitterAPIExchange.php: -------------------------------------------------------------------------------- 1 | 11 | * @license MIT License 12 | * @link http://github.com/j7mbo/twitter-api-php 13 | */ 14 | class TwitterAPIExchange 15 | { 16 | private $oauth_access_token; 17 | private $oauth_access_token_secret; 18 | private $consumer_key; 19 | private $consumer_secret; 20 | private $postfields; 21 | private $getfield; 22 | protected $oauth; 23 | public $url; 24 | 25 | /** 26 | * Create the API access object. Requires an array of settings:: 27 | * oauth access token, oauth access token secret, consumer key, consumer secret 28 | * These are all available by creating your own application on dev.twitter.com 29 | * Requires the cURL library 30 | * 31 | * @param array $settings 32 | */ 33 | public function __construct(array $settings) 34 | { 35 | if (!in_array('curl', get_loaded_extensions())) 36 | { 37 | throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html'); 38 | } 39 | 40 | if (!isset($settings['oauth_access_token']) 41 | || !isset($settings['oauth_access_token_secret']) 42 | || !isset($settings['consumer_key']) 43 | || !isset($settings['consumer_secret'])) 44 | { 45 | throw new Exception('Make sure you are passing in the correct parameters'); 46 | } 47 | 48 | $this->oauth_access_token = $settings['oauth_access_token']; 49 | $this->oauth_access_token_secret = $settings['oauth_access_token_secret']; 50 | $this->consumer_key = $settings['consumer_key']; 51 | $this->consumer_secret = $settings['consumer_secret']; 52 | } 53 | 54 | /** 55 | * Set postfields array, example: array('screen_name' => 'J7mbo') 56 | * 57 | * @param array $array Array of parameters to send to API 58 | * 59 | * @return TwitterAPIExchange Instance of self for method chaining 60 | */ 61 | public function setPostfields(array $array) 62 | { 63 | if (!is_null($this->getGetfield())) 64 | { 65 | throw new Exception('You can only choose get OR post fields.'); 66 | } 67 | 68 | if (isset($array['status']) && substr($array['status'], 0, 1) === '@') 69 | { 70 | $array['status'] = sprintf("\0%s", $array['status']); 71 | } 72 | 73 | $this->postfields = $array; 74 | 75 | return $this; 76 | } 77 | 78 | /** 79 | * Set getfield string, example: '?screen_name=J7mbo' 80 | * 81 | * @param string $string Get key and value pairs as string 82 | * 83 | * @return \TwitterAPIExchange Instance of self for method chaining 84 | */ 85 | public function setGetfield($string) 86 | { 87 | if (!is_null($this->getPostfields())) 88 | { 89 | throw new Exception('You can only choose get OR post fields.'); 90 | } 91 | 92 | $search = array('#', ',', '+', ':'); 93 | $replace = array('%23', '%2C', '%2B', '%3A'); 94 | $string = str_replace($search, $replace, $string); 95 | 96 | $this->getfield = $string; 97 | 98 | return $this; 99 | } 100 | 101 | /** 102 | * Get getfield string (simple getter) 103 | * 104 | * @return string $this->getfields 105 | */ 106 | public function getGetfield() 107 | { 108 | return $this->getfield; 109 | } 110 | 111 | /** 112 | * Get postfields array (simple getter) 113 | * 114 | * @return array $this->postfields 115 | */ 116 | public function getPostfields() 117 | { 118 | return $this->postfields; 119 | } 120 | 121 | /** 122 | * Build the Oauth object using params set in construct and additionals 123 | * passed to this method. For v1.1, see: https://dev.twitter.com/docs/api/1.1 124 | * 125 | * @param string $url The API url to use. Example: https://api.twitter.com/1.1/search/tweets.json 126 | * @param string $requestMethod Either POST or GET 127 | * @return \TwitterAPIExchange Instance of self for method chaining 128 | */ 129 | public function buildOauth($url, $requestMethod) 130 | { 131 | if (!in_array(strtolower($requestMethod), array('post', 'get'))) 132 | { 133 | throw new Exception('Request method must be either POST or GET'); 134 | } 135 | 136 | $consumer_key = $this->consumer_key; 137 | $consumer_secret = $this->consumer_secret; 138 | $oauth_access_token = $this->oauth_access_token; 139 | $oauth_access_token_secret = $this->oauth_access_token_secret; 140 | 141 | $oauth = array( 142 | 'oauth_consumer_key' => $consumer_key, 143 | 'oauth_nonce' => time(), 144 | 'oauth_signature_method' => 'HMAC-SHA1', 145 | 'oauth_token' => $oauth_access_token, 146 | 'oauth_timestamp' => time(), 147 | 'oauth_version' => '1.0' 148 | ); 149 | 150 | $getfield = $this->getGetfield(); 151 | 152 | if (!is_null($getfield)) 153 | { 154 | $getfields = str_replace('?', '', explode('&', $getfield)); 155 | foreach ($getfields as $g) 156 | { 157 | $split = explode('=', $g); 158 | $oauth[$split[0]] = $split[1]; 159 | } 160 | } 161 | 162 | $base_info = $this->buildBaseString($url, $requestMethod, $oauth); 163 | $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret); 164 | $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true)); 165 | $oauth['oauth_signature'] = $oauth_signature; 166 | 167 | $this->url = $url; 168 | $this->oauth = $oauth; 169 | 170 | return $this; 171 | } 172 | 173 | /** 174 | * Perform the actual data retrieval from the API 175 | * 176 | * @param boolean $return If true, returns data. 177 | * 178 | * @return string json If $return param is true, returns json data. 179 | */ 180 | public function performRequest($return = true) 181 | { 182 | if (!is_bool($return)) 183 | { 184 | throw new Exception('performRequest parameter must be true or false'); 185 | } 186 | 187 | $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:'); 188 | 189 | $getfield = $this->getGetfield(); 190 | $postfields = $this->getPostfields(); 191 | 192 | $options = array( 193 | CURLOPT_HTTPHEADER => $header, 194 | CURLOPT_HEADER => false, 195 | CURLOPT_URL => $this->url, 196 | CURLOPT_RETURNTRANSFER => true, 197 | CURLOPT_TIMEOUT => 10, 198 | ); 199 | 200 | if (!is_null($postfields)) 201 | { 202 | $options[CURLOPT_POSTFIELDS] = $postfields; 203 | } 204 | else 205 | { 206 | if ($getfield !== '') 207 | { 208 | $options[CURLOPT_URL] .= $getfield; 209 | } 210 | } 211 | 212 | $feed = curl_init(); 213 | curl_setopt_array($feed, $options); 214 | $json = curl_exec($feed); 215 | curl_close($feed); 216 | 217 | if ($return) { return $json; } 218 | } 219 | 220 | /** 221 | * Private method to generate the base string used by cURL 222 | * 223 | * @param string $baseURI 224 | * @param string $method 225 | * @param array $params 226 | * 227 | * @return string Built base string 228 | */ 229 | private function buildBaseString($baseURI, $method, $params) 230 | { 231 | $return = array(); 232 | ksort($params); 233 | 234 | foreach($params as $key=>$value) 235 | { 236 | $return[] = "$key=" . $value; 237 | } 238 | 239 | return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $return)); 240 | } 241 | 242 | /** 243 | * Private method to generate authorization header used by cURL 244 | * 245 | * @param array $oauth Array of oauth data generated by buildOauth() 246 | * 247 | * @return string $return Header used by cURL for request 248 | */ 249 | private function buildAuthorizationHeader($oauth) 250 | { 251 | $return = 'Authorization: OAuth '; 252 | $values = array(); 253 | 254 | foreach($oauth as $key => $value) 255 | { 256 | $values[] = "$key=\"" . rawurlencode($value) . "\""; 257 | } 258 | 259 | $return .= implode(', ', $values); 260 | return $return; 261 | } 262 | 263 | } 264 | -------------------------------------------------------------------------------- /enviarTweet.php: -------------------------------------------------------------------------------- 1 | "", 8 | 'oauth_access_token_secret' => "", 9 | 'consumer_key' => "", 10 | 'consumer_secret' => "" 11 | ); 12 | /** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/ 13 | $url = 'https://api.twitter.com/1.1/statuses/update.json'; 14 | // $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json'; 15 | $requestMethod = 'POST'; 16 | /** POST fields required by the URL above. See relevant docs as above **/ 17 | $postfields = array( 'status' => $mensaje, ); 18 | /** Perform a POST request and echo the response **/ 19 | $twitter = new TwitterAPIExchange($settings); 20 | return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); 21 | } 22 | 23 | $mensaje = "Tutorial realizado con éxito en @GeekyTheory. #PHP + #Twitter: Cómo enviar tweets desde PHP | http://geekytheory.com/php-twitter-como-enviar-tweets-desde-php" 24 | $respuesta = sendTweet($mensaje); 25 | $json = json_decode($respuesta); 26 | 27 | echo ''; 28 | echo "Tweet Enviado por: ".$json->user->name." (@".$json->user->screen_name.")"; 29 | echo "
"; 30 | echo "Tweet: ".$json->text; 31 | echo "
"; 32 | echo "Tweet ID: ".$json->id_str; 33 | echo "
"; 34 | echo "Fecha Envio: ".$json->created_at; 35 | ?> 36 | -------------------------------------------------------------------------------- /hacerFav.php: -------------------------------------------------------------------------------- 1 | "", 8 | 'oauth_access_token_secret' => "", 9 | 'consumer_key' => "", 10 | 'consumer_secret' => "" 11 | ); 12 | $url = 'https://api.twitter.com/1.1/favorites/create.json'; 13 | // $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json'; 14 | $requestMethod = 'POST'; 15 | /** POST fields required by the URL above. See relevant docs as above **/ 16 | $postfields = array( 'id' => $id_tweet,'' => "" ); 17 | /** Perform a POST request and echo the response **/ 18 | $twitter = new TwitterAPIExchange($settings); 19 | return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); 20 | } 21 | 22 | doFAV("470880387716378624"); -------------------------------------------------------------------------------- /hacerFollow.php: -------------------------------------------------------------------------------- 1 | "", 8 | 'oauth_access_token_secret' => "", 9 | 'consumer_key' => "", 10 | 'consumer_secret' => "" 11 | ); 12 | $url = 'https://api.twitter.com/1.1/friendships/create.json'; 13 | // $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json'; 14 | $requestMethod = 'POST'; 15 | /** POST fields required by the URL above. See relevant docs as above **/ 16 | $postfields = array( 'screen_name' => $usuario,'follow' => "true" ); 17 | /** Perform a POST request and echo the response **/ 18 | $twitter = new TwitterAPIExchange($settings); 19 | return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); 20 | } 21 | 22 | //$mensaje = "Tutorial realizado con éxito en @GeekyTheory. #PHP + #Twitter: Cómo enviar tweets desde PHP | http://geekytheory.com/php-twitter-como-enviar-tweets-desde-php" 23 | //$mensaje = "Prueba del envío de tweets desde #PHP con la API de Twitter para el próximo tutorial en @GeekyTheory"; 24 | $respuesta = follow("geeksphone"); 25 | echo $respuesta; 26 | //$respuesta = '{"created_at":"Sun May 25 22:01:53 +0000 2014","id":470686216393093120,"id_str":"470686216393093120","text":"Prueba del env\u00edo de tweets desde #PHP con la API de Twitter para el pr\u00f3ximo tutorial en @GeekyTheory","source":"\u003ca href=\"http:\/\/geekytheory.com\" rel=\"nofollow\"\u003eGeekyPHP\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":309084573,"id_str":"309084573","name":"Alejandro Esquiva","screen_name":"Alex_Esquiva","location":"Bigastro","description":"Estudiante Ingenier\u00eda de Telecomunicaciones, Administrador y Redactor http:\/\/t.co\/jxmw2XoiJT, @geekytheory #arduino #raspberrypi #php #java #coding","url":"http:\/\/t.co\/KTr3NdjbKH","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/KTr3NdjbKH","expanded_url":"http:\/\/about.me\/alejandro.esquiva","display_url":"about.me\/alejandro.esqu\u2026","indices":[0,22]}]},"description":{"urls":[{"url":"http:\/\/t.co\/jxmw2XoiJT","expanded_url":"http:\/\/geekytheory.com","display_url":"geekytheory.com","indices":[70,92]}]}},"protected":false,"followers_count":226,"friends_count":193,"listed_count":10,"created_at":"Wed Jun 01 14:14:13 +0000 2011","favourites_count":48,"utc_offset":-7200,"time_zone":"Greenland","geo_enabled":true,"verified":false,"statuses_count":1162,"lang":"es","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/262404222\/Patterns_20110304_Flower-pattern.jpg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/262404222\/Patterns_20110304_Flower-pattern.jpg","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/378800000425513708\/cc332bd948f65a97f4da8810e5d7a91d_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/378800000425513708\/cc332bd948f65a97f4da8810e5d7a91d_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/309084573\/1378585307","profile_link_color":"009999","profile_sidebar_border_color":"EEEEEE","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"PHP","indices":[33,37]}],"symbols":[],"urls":[],"user_mentions":[{"screen_name":"GeekyTheory","name":"GeekyTheory","id":821970349,"id_str":"821970349","indices":[88,100]}]},"favorited":false,"retweeted":false,"lang":"es"}'; 27 | $json = json_decode($respuesta); 28 | 29 | echo ''; 30 | echo "Usuario: ".$json->name." (@".$json->screen_name.")"; 31 | echo "
"; 32 | echo "ID USER: ".$json->id_str; 33 | echo "
"; 34 | echo "Fecha Envio: ".$json->created_at; 35 | ?> 36 | -------------------------------------------------------------------------------- /hacerRT.php: -------------------------------------------------------------------------------- 1 | "", 8 | 'oauth_access_token_secret' => "", 9 | 'consumer_key' => "", 10 | 'consumer_secret' => "" 11 | ); 12 | $url = 'https://api.twitter.com/1.1/statuses/retweet/'.$id_tweet.'.json'; 13 | // $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json'; 14 | $requestMethod = 'POST'; 15 | /** POST fields required by the URL above. See relevant docs as above **/ 16 | $postfields = array( '' => '','' => "" ); 17 | /** Perform a POST request and echo the response **/ 18 | $twitter = new TwitterAPIExchange($settings); 19 | return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); 20 | } 21 | 22 | doRT("470880387716378624"); -------------------------------------------------------------------------------- /hacerUnfollow.php: -------------------------------------------------------------------------------- 1 | "", 8 | 'oauth_access_token_secret' => "", 9 | 'consumer_key' => "", 10 | 'consumer_secret' => "" 11 | ); 12 | $url = 'https://api.twitter.com/1.1/friendships/destroy.json'; 13 | // $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json'; 14 | $requestMethod = 'POST'; 15 | /** POST fields required by the URL above. See relevant docs as above **/ 16 | $postfields = array( 'screen_name' => $usuario, ); 17 | /** Perform a POST request and echo the response **/ 18 | $twitter = new TwitterAPIExchange($settings); 19 | return $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); 20 | } 21 | 22 | //$mensaje = "Tutorial realizado con éxito en @GeekyTheory. #PHP + #Twitter: Cómo enviar tweets desde PHP | http://geekytheory.com/php-twitter-como-enviar-tweets-desde-php" 23 | //$mensaje = "Prueba del envío de tweets desde #PHP con la API de Twitter para el próximo tutorial en @GeekyTheory"; 24 | $respuesta = unfollow("geeksphone"); -------------------------------------------------------------------------------- /insertarBD.php: -------------------------------------------------------------------------------- 1 | "", 15 | 'oauth_access_token_secret' => "", 16 | 'consumer_key' => "", 17 | 'consumer_secret' => "" 18 | ); 19 | 20 | if($num_tweets>100) $num_tweets = 100; 21 | 22 | $url = 'https://api.twitter.com/1.1/search/tweets.json'; 23 | $getfield = '?q='.$query.'&count='.$num_tweets; 24 | 25 | $requestMethod = 'GET'; 26 | $twitter = new TwitterAPIExchange($settings); 27 | $json = $twitter->setGetfield($getfield) 28 | ->buildOauth($url, $requestMethod) 29 | ->performRequest(); 30 | return $json; 31 | } 32 | 33 | function insertarTweetInfo( 34 | $id_tweet, 35 | $tweet, 36 | $rts, 37 | $favs, 38 | $fecha_creacion, 39 | $usuario, 40 | $url_imagen, 41 | $followers, 42 | $followings, 43 | $num_tweets 44 | ){ 45 | 46 | //Creamos la conexión a la base de datos 47 | $conexion = mysqli_connect("localhost", "root", "", "twitterdata"); 48 | //Comprobamos laconexión 49 | if($conexion){ 50 | }else{ 51 | die('Ha sucedido un error inexperador en la conexion de la base de datos
'); 52 | } 53 | //Codificación de la base de datos en utf8 54 | mysqli_query ($conexion,"SET NAMES 'utf8'"); 55 | mysqli_set_charset($conexion, "utf8"); 56 | 57 | //Creamos la sentencia SQL para insertar los datos de entrada 58 | $sql = "insert into tweets (id_tweet,tweet,rt,fav,fecha_creacion,usuario,url_imagen,followers,followings,num_tweets) 59 | values (".$id_tweet.",'".$tweet."',".$rts.",".$favs.",'".$fecha_creacion."','".$usuario."','".$url_imagen."',".$followers.",".$followings.",".$num_tweets.");"; 60 | $consulta = mysqli_query($conexion,$sql); 61 | //Comprobamos si la consulta ha tenido éxito 62 | if($consulta){ 63 | }else{ 64 | die("No se ha podido insertar en la base de datos

".mysqli_error($conexion)); 65 | } 66 | 67 | //Cerramos la conexión de la base de datos 68 | $close = mysqli_close($conexion); 69 | if($close){ 70 | }else{ 71 | Die('Ha sucedido un error inexperado en la desconexion de la base de datos
'); 72 | } 73 | } 74 | 75 | //Obtenemos el JSON con la información 76 | $json = getJsonTweets("GeekyTheory", 10); 77 | //Codificamos el json 78 | $json = json_decode($json); 79 | //obtenemos un array con las filas, es decir con cada tweet. 80 | $rows = $json->statuses; 81 | //Iteramos los tweets, extraemos la información y la almacenamos en la base de datos. 82 | for($i=0;$iid_str; 84 | $tweet = $rows[$i]->text; 85 | $rts = $rows[$i]->retweet_count; 86 | $favs = $rows[$i]->favorite_count; 87 | $fecha_creacion = $rows[$i]->created_at; 88 | $usuario = $rows[0]->user->screen_name; 89 | $url_imagen = $rows[0]->user->profile_image_url; 90 | $followers = $rows[0]->user->followers_count; 91 | $following = $rows[0]->user->friends_count; 92 | $num_tweets = $rows[0]->user->statuses_count; 93 | 94 | //insertamos los datos en la base de datos 95 | insertarTweetInfo($id_tweet, $tweet, $rts, $favs, $fecha_creacion, $usuario, $url_imagen, $followers, $followings, $num_tweets); 96 | } -------------------------------------------------------------------------------- /nbproject/project.properties: -------------------------------------------------------------------------------- 1 | include.path=${php.global.include.path} 2 | php.version=PHP_54 3 | source.encoding=UTF-8 4 | src.dir=. 5 | tags.asp=false 6 | tags.short=false 7 | web.root=. 8 | -------------------------------------------------------------------------------- /nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.php.project 4 | 5 | 6 | TutorialesTwitter 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /searchTweets.php: -------------------------------------------------------------------------------- 1 | "", 12 | 'oauth_access_token_secret' => "", 13 | 'consumer_key' => "", 14 | 'consumer_secret' => "" 15 | ); 16 | 17 | if($num_tweets>100) $num_tweets = 100; 18 | 19 | $url = 'https://api.twitter.com/1.1/search/tweets.json'; 20 | $getfield = '?q='.$query.'&count='.$num_tweets; 21 | 22 | $requestMethod = 'GET'; 23 | $twitter = new TwitterAPIExchange($settings); 24 | $json = $twitter->setGetfield($getfield) 25 | ->buildOauth($url, $requestMethod) 26 | ->performRequest(); 27 | return $json; 28 | } 29 | 30 | --------------------------------------------------------------------------------