このブログを検索

ラベル php の投稿を表示しています。 すべての投稿を表示
ラベル php の投稿を表示しています。 すべての投稿を表示

2018/01/28

twitteroauth

twitter apiを使ったphpのソースを公開したが重要な欠陥に気づいて非公開にした。
そして修正しているうちに認証できなくなってしまった。
調べているとoauthで使用しているtwitteroauthが更新されていたので、
アップデートがてら作り直すことにした。

最新リリースを持ってくる。
https://github.com/abraham/twitteroauth/releases

0.7.4が去年の7/1にリリースされていた。

今のバージョンはなんだろうと見てみるとバージョンが書かれている場所がわからないが
ファイルのタイムスタンプが 2015 8/19なので0.5.4だ。クソ古い。

解凍の仕方も忘れている。

tar -zxvf 0.7.4.tar.gz

参考
https://qiita.com/sofpyon/items/982fe3a9ccebd8702867


自分のkeyを定義したphpファイルを作る。
common.php

これは前に作ったものをそのまま使える。

login.php

上記サイトのソースがコメントまで同じだ。
前回もこの人のを参考にしたのか?
requireのパスだけ今回のものに変える。

mypage.php
を作って動かす。

http error 500になる。

下記2行をソースの最初に書いてエラーメッセージを表示させる。

ini_set("display_errors", On);
error_reporting(E_ALL);


Notice: Undefined index: access_token in /var/www/html/ssl/bl/mypage.php on line 14 Parse error: syntax error, unexpected '[' in /var/www/html/ssl/bl/twitteroauth-0.7.4/src/TwitterOAuth.php on line 128

これはphpのバージョンが古いために出るらしい。
今のphpのバージョンは5.3.3

自動アップデート(名前は忘れた)しているがphpは上がっていない。
レポジトリを変えないとダメなようだ。

こちらを参考にphpをアップデート

https://qiita.com/ozawan/items/caf6e7ddec7c6b31f01e

バージョンを確認...... 変わってない!

apacheを再起動しないとダメだそうだ。

service httpd restart

変わった。

今度は以下のエラー。

Notice: Undefined index: access_token in /xxxx/mypage.php on line 14
object(stdClass)#3 (1) { ["errors"]=> array(1) { [0]=> object(stdClass)#7 (2) { ["message"]=> string(53) "Your credentials do not allow access to this resource" ["code"]=> int(220) } } }

twitteroauth, phpのバージョンをあげる前と同じだ。

許可されていないAPIを呼び出した時などに出るエラーのようだが、
アクセストークンを取り出しているだけだ。

APIの利用制限に引っかかったのか?












2018/01/27

twitterでブロックしているユーザの表示、ブロック解除

修正した。

ブラックリストに加えて、NG wordリストを作成し、
NG wordを含むアカウントがブロックされている場合はブロック解除しないようにした。

それから、ブラックリストへの登録は今までは手作業であったが、
ブロックしているユーザを選択して登録できるようにした。

※ドメイン名は example.comに置き換えてある。

<?php
session_start();
require_once 'common.php';
require_once 'vendor/abraham/twitteroauth/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get("account/verify_credentials");
$blocking_users = array();
echo '<img src="' . $user->profile_image_url . '">' . ' ' . $user->name . ' is blocking following users.<br><br>';

$showdetail = 0;
$black_list = @file('blacklist.txt');
$black_list = array_map('trim', $black_list);
$ngwords = @file('ngwords.txt');
$ngwords = array_map('trim', $ngwords);
echo '<a href="https://example.com/bl/mypage.php?mode=unblock">unblock all</a><br><hr>';
echo '<a href="https://example.com/bl/mypage.php">refresh</a><hr>';
echo '<a href="https://example.com/bl/addbl.php">add blacklist</a><br><br><hr>';
echo '<a href="https://example.com/bl/mypage.php?mode=reblock">reblock users in bl</a><br><hr>';
echo '<a href="https://example.com/bl/edbl.php">edit blacklist</a><hr>';
echo '<a href="https://example.com/bl/mypage.php?mode=logout">logout</a><br>';
$blu_file = 'blocking.txt';
$req2 = $connection->OAuthRequest('https://api.twitter.com/1.1/blocks/list.json','GET',array('count'=>'100'));
$blocks = json_decode($req2,true);
if (isset($blocks) && empty($blocks->errors)) {
        echo '<hr>';
        foreach ($blocks as $val) {
                for($i = 0; $i<count($val)-1;$i++)
                {
                        $blocking_user = $val[$i]['screen_name'];
                        $is_ng = False;
                        foreach($ngwords as $ng) {
                                if(stripos($blocking_user, $ng) !== false) {
                                        $is_ng = True;
                                }
                        }
                        if ($is_ng) {
                                echo '<font size="1">* NG * </font>';
                                $showdetail = 0;
                        } elseif (in_array($blocking_user,$black_list)) {
                                echo '<font size="1">* BL * </font>';
                                $showdetail = 0;
                        } else {
                                $showdetail = 1;
                        }
                        echo
                                '<font size="1">' . $blocking_user . '  ' .$val[$i]['name'] . '   '
                                . '<font color=blue>' . $blocking_user . '</font><br>' ;
                                if ($showdetail > 0) {
                                        echo '<blockquote>' . '<img src="' . $val[$i]['profile_image_url'] . '"><br>'
                                        . $val[$i]['description'] . '<br></blockquote>';
                                        $blu_current .= $blocking_user . "\n";
                                }
                        $blocking_users_list[] = $blocking_user;
                }
        }
} else {
        echo 'you are blocking nobody.';
}
file_put_contents($blu_file, $blu_current);
if(isset($_GET['mode']))        {
        if ($_GET['mode'] == 'unblock') {
                foreach($blocking_users_list as $a)     {
                        $is_ng = False;
                        foreach($ngwords as $ng) {
                                if(stripos($a, $ng) !== false) {
                                        $is_ng = True;
                                }
                        }
                        if (in_array($a,$black_list)) {
                                echo $a . " is in blacklist.<br>";
                        } elseif($is_ng) {
                                echo $a . " contains ngwords.<br>";
                        }  else {
                                $result = $connection->OAuthRequest('https://api.twitter.com/1.1/blocks/destroy.json','POST'
                                        ,array('screen_name'=>$a));
                                $j = json_decode($result,true);
                                if (isset($j)) {
                                        echo $j['screen_name']." is unblocked.<br>";
                                }
                        }
                }
        } elseif ($_GET['mode'] == 'reblock') {
                        foreach($black_list as $a)     {
                                $result = $connection->OAuthRequest('https://api.twitter.com/1.1/blocks/create.json','POST'
                                        ,array('screen_name'=>$a));
                                $j = json_decode($result,true);
                                if (isset($j)) {
                                        echo $j['screen_name']." is blocked.<br>";
                                }
                        }
                }
        header("location:https://example.com/bl/mypage.php");
        exit();
}
if(isset($_GET['mode']))        {
        if ($_GET['mode'] == 'logout')  {
                session_destroy();
                header("location:https://example.com/bl/login.php");
        }
}
?>


ブラックリスト登録

--------------------------
<form name='form1' action = 'addbl_result.php' method='get' >
<?php
$array = file("blocking.txt");
for($i = 0 ; $i < count($array); $i++){
        echo '<input name="blocking[]" type="checkbox" value=' . $array[$i] .'>' . $array[$i] . '<br>' ;
}
?>
<input type="submit" vlaue="submit">
</form>

------------------------------

<?php
$bl_file = 'blacklist.txt';
$current = file_get_contents($bl_file);

if(empty($_GET["blocking"])){
     echo "何も選んでません";
}else{
     $blocking = $_GET["blocking"];
     foreach($blocking as $value){
#       echo $value . '<br>';
        $current .= $value. "\n";
     }
}
file_put_contents($bl_file, $current);
header("location:http://example.com/bl/mypage.php");
exit();
?>

2016/05/02

PHP twitteroauth ブロックしているユーザーのアンブロック

ブロック解除もできた。

(前回 http://blog.monqy.net/2016/05/php-twitteroauth.html の続き)

--------------------------------------
#ブロックしているユーザーを取得

$req2 = $connection->OAuthRequest('https://api.twitter.com/1.1/blocks/list.json','GET',array('count'=>'100'));
$blocks = json_decode($req2,true);
if (isset($blocks) && empty($blocks->errors)) {

        echo '<hr>';
        foreach ($blocks as $val) {

                for($i = 0; $i<count($val)-1;$i++)
                {
                        echo
                                $val[$i]['name'] . '<br>'
                                . '<img src="' . $val[$i]['profile_image_url'] . '"><br>'
                                . $val[$i]['screen_name'] . '<br>'
                                . '<hr>';

#ブロックしているユーザーのscreen_nameをarrayに格納
                        $blocking_users[] = $val[$i]['screen_name'];
                }
        }
} else {
        echo 'you are blocking nobody.';
}



#スクリプトに引数「mode=unblock」が指定された場合はunblockする

if(isset($_GET['mode']))        {
        if ($_GET['mode'] == 'unblock') {
                foreach($blocking_users as $a)  {
                        $result = $connection->OAuthRequest('https://api.twitter.com/1.1/blocks/destroy.json','POST',array('screen_name'=>$a));
                        $j = json_decode($result,true);
                        if (isset($j)) {
                                echo $j['screen_name']." is unblocked.<br>";
                        }
                }
        }
}
----------------------------------------------

OAuthRequestの後にAPIのURLを指定すればなんでもできるようだ。


$result = $connection->OAuthRequest(<URL>,<メソッド>,<パラメータ>);







PHP + twitteroauth ブロックしているユーザーの一覧表示

ついにできた。

(全体は下記を参照)
http://blog.monqy.net/2016/05/phptwitter-api-oauth.html



<?php

session_start();

require_once 'common.php';
require_once 'vendor/abraham/twitteroauth/autoload.php';

use Abraham\TwitterOAuth\TwitterOAuth;

$access_token = $_SESSION['access_token'];

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_s
ecret']);

$user = $connection->get("account/verify_credentials");

echo 'hello, ';
echo $user->name;


$req2 = $connection->OAuthRequest('https://api.twitter.com/1.1/blocks/list.json','GET',array('count'=>'100'));
$blocks = json_decode($req2,true);
if (isset($blocks) && empty($blocks->errors)) {

        echo '<hr>';
        foreach ($blocks as $val) {

                for($i = 0; $i<count($val)-1;$i++)
                {
                        echo
                                $val[$i]['name'] . '<br>'
                                . '<img src="' . $val[$i]['profile_image_url'] . '"><br>'
                                . $val[$i]['screen_name'] . '<br>'
                                . '<hr>';
                }
        }
        echo '<hr>';
} else {
        echo 'you are blocking nobody.';
}

?>

PHPでtwitter api のoauthが簡単にできるようになった

thanks to abraham

https://twitteroauth.com/


oauthに再挑戦。

久しぶりだから情報も増えているだろうと期待して。


http://qiita.com/sofpyon/items/982fe3a9ccebd8702867

phpか...

まあいいや、やってみよう。


https://twitteroauth.com/


composer ?

いれる。

phpのバージョンが古いと言われる。


http://qiita.com/zaburo/items/fd67b294c610d54c3aee

レポジトリを変更する。

5.4.45にする。



・・・・


めんどくさいので結果だけ。

以下の情報をほぼそのまま参考にした。

http://qiita.com/sofpyon/items/982fe3a9ccebd8702867



composerで twitteroauthをインストールするときは、
実際にphpスクリプトを動かすディレクトリにする。


php 5.3だから出るエラーが出てしまった。
5.4.45にあげたのに。

composerを入れた後だったからだろうか?
よくわからないが phpの書き方を変えた。



/var/www/html/

で動かすとして、

そこに、下記ファイルを作る。

common.php
login.php
callback.php
mypage.php


中身


# cat common.php
<?php

define( 'CONSUMER_KEY', '------ your consumuer key -----' );
define( 'CONSUMER_SECRET', '------ your consumuer secret -----' );
define( 'OAUTH_CALLBACK', 'http://example.com/callback.php' ); ※URLは仮





# cat login.php
<?php

session_start();

require_once 'common.php';
require_once 'vendor/abraham/twitteroauth/autoload.php';

use Abraham\TwitterOAuth\TwitterOAuth;

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

$url = $connection->url('oauth/authenticate', array('oauth_token' => $request_token['oauth_token']));

header( 'location: '. $url );






# cat callback.php
<?php

session_start();

require_once 'common.php';
require_once 'vendor/abraham/twitteroauth/autoload.php';

use Abraham\TwitterOAuth\TwitterOAuth;

$request_token = array();
$request_token['oauth_token'] = $_SESSION['oauth_token'];
$request_token['oauth_token_secret'] = $_SESSION['oauth_token_secret'];

if (isset($_REQUEST['oauth_token']) && $request_token['oauth_token'] !== $_REQUEST['oauth_token']) {
    die( 'Error!' );
}

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);

$_SESSION['access_token'] = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));

session_regenerate_id();

header( 'location: /bl/mypage.php' );






# cat mypage.php
<?php

session_start();

require_once 'common.php';
require_once 'vendor/abraham/twitteroauth/autoload.php';

use Abraham\TwitterOAuth\TwitterOAuth;

$access_token = $_SESSION['access_token'];

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

$user = $connection->get("account/verify_credentials");

echo 'hello, ';
echo $user->name;





http://example.com/login.php ※URLはサンプル

にブラウザでアクセスする。


アプリへのアクセスを許可するかとたずねられて許可すると、


あなたのnameが「ほげほげ君」だとしたら、


hello, ほげほげ君


と表示される。




oauth自体はすごく簡単にできるようになった。

ここまでできてしまえば、あとは自分が取得したい情報を表示、
操作したいAPIを使ってやりたいことをやればよい。


・・・が、そこがよくわからない・・・。



本当はpythonでやりたい。
pythonにも同様のライブラリがあるようなので、今度試してみたい。

2013/01/25

phpの連想配列

twitter apiを使っていて、perlでうまくいかないのでよく使われているphpのtwitteroauthでやっているのだが、json形式のデータから目指す値を取り出す方法がよくわからない。

phpの基礎からやっていく。

まず、連想配列。

<?php

$beatles = array (
'guitar' => 'george',
'bass' => 'paul',
'drums' => 'ringo',
'vocal' => 'john'
);

echo $beatles['guitar'];

echo "\n";

?>

実行結果

# php hai.php
george 今度は、json形式のデータを作り、それを配列に戻して値を取り出す。

<?php
$arr = array('John' => 'Lennon', 'Paul' => 'McCartney', 'George' => 'Harrison', 'Ringo' => 'Starr');

echo $arr['John']."\n";
echo $arr['Ringo']."\n";

echo "\n";

$json = json_encode($arr);

var_dump($json);

echo "\n";

$arr2 = json_decode($json);
var_dump($arr2);


$arr2 = json_decode($json,true);
var_dump($arr2);

echo $arr2['John']."\n";

?>

実行結果

# php a.php
Lennon
Starr

string(72) "{"John":"Lennon","Paul":"McCartney","George":"Harrison","Ringo":"Starr"}"

object(stdClass)#1 (4) {
["John"]=>
string(6) "Lennon"
["Paul"]=>
string(9) "McCartney"
["George"]=>
string(8) "Harrison"
["Ringo"]=>
string(5) "Starr"
}
array(4) {
["John"]=>
string(6) "Lennon"
["Paul"]=>
string(9) "McCartney"
["George"]=>
string(8) "Harrison"
["Ringo"]=>
string(5) "Starr"
}
Lennon
json_decodeで、オプション trueをつけると連想配列になる。つけない場合はvar_dumpすると object(stdClass) となっており、値を参照できなかった。どういう用途に使うのか?




2013/01/24

phpで、oauthで認証後、そのユーザがブロックしているユーザを表示する

※このエントリーは古いです。

oauthについて再確認したエントリーはこちら

http://blog.monqy.net/2016/05/phptwitter-api-oauth.html

http://blog.monqy.net/2016/05/php-twitteroauth.html

http://blog.monqy.net/2016/05/php-twitteroauth_2.html


-----------------------------------------------------------------------------


アブラハムさんのサンプルhttps://github.com/abraham/twitteroauthをちょこっといじったもの。

<?php
/**
* @file
* User has successfully authenticated with Twitter. Access tokens saved to session and DB.
*/

/* Load required lib files. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];

/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

/* If method is set change API call made. Test is called by default. */

$req1 = $connection->OAuthRequest("https://api.twitter.com/1.1/account/verify_credentials.json","GET");
$req2 = $connection->OAuthRequest("https://api.twitter.com/1.1/blocks/list.json","GET");
$json1 = json_decode($req1,true);
$json2 = json_decode($req2,true);

/* Include HTML to display on the page */
include('html.inc');


html.incは

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Twitter OAuth in PHP</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
img {border-width: 0}
* {font-family:'Lucida Grande', sans-serif;}
</style>
</head>
<body>
<div>
<h2>Welcome to a Twitter OAuth PHP example.</h2>

<p>This site is a basic showcase of Twitters OAuth authentication method. If you are having issues try <a href='./clearsessions.php'>clearing your session</a>.</p>

<p>
Links:
<a href='http://github.com/abraham/twitteroauth'>Source Code</a> &amp;
<a href='http://wiki.github.com/abraham/twitteroauth/documentation'>Documentation</a> |
Contact @<a href='http://twitter.com/abraham'>abraham</a>
</p>
<hr />
<?php if (isset($menu)) { ?>
<?php echo $menu; ?>
<?php } ?>
</div>
<?php if (isset($status_text)) { ?>
<?php echo '<h3>'.$status_text.'</h3>'; ?>
<?php } ?>
<p>
<pre>
<?php print_r($content); ?>
<hr>
<?php print($json1[screen_name])." is blocking <br><br>";
foreach($json2[users] as $key => $value){
print $value[screen_name].'<br>';
}
?>
</pre>
</p>

</body>
</html>


いろいろとダサいところはあるでしょうが、

とりあえずこれでブロックユーザ一覧が表示できる。

ハマったのは、$contentのprint_rを消すと、ユーザに認証させるためのボタンが消えてしまうことだった。

どうしてそうなるのかはいまだによくわからないが、とりあえずこいつを消してはいけない。

つぎはblockの解除だ。

ここまでくればあとはいけるだろう。




2012/12/28

phpのcgi

OSはデフォルトのCentOS6

cgiはperlで書いている。

phpでも何か動かせるようにしようとしたのだが、

phpのスクリプトを動かすと、htmlタグがそのまま表示されてしまう。

apacheのhttpd.confで、

AddType application/x-httpd-php .php

を書くと、ファイルがダウンロードされる。

コメントにすると、実行されるがhtmlタグがそのまま表示される。

WEBをさがしてみたが同じ状況の人がいない・・・。

「ソースが表示されてしまう」

「ダウンロードしてしまう」

という人はいる。

httpd.confの設定がどうこう、という情報はあるのだが、さくらのVPSでうまくいっている人は特に変更していない。

が、phpのバージョンが違う。

一応、あわせてみるか・・・。

「remiリポジトリ」を登録する必要があるとのことなので、


rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-5.rpm


その後、以下を実行。


yum install php-mbstring --enablerepo=remi
yum install php-gd --enablerepo=remi
yum install php-pear --enablerepo=remi
yum install php-mcrypt --enablerepo=remi
yum install php-mysql --enablerepo=remi
yum install php-devel --enablerepo=remi


バージョンは


[hoge]# php -v
PHP 5.4.10 (cli) (built: Dec 19 2012 11:45:14)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies


動いた・・・

httpd.confのAddHandler, AddType applicationとかはデフォルトに戻した。

バージョンが違うというより、その後に入れたモジュールが入ったせいじゃないかな・・・

くわしくはわからん。

あと、php.iniのtimezoneの設定を変更


[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone ="Asia/Tokyo"


その下に、コメントアウトされているがlatitudeとかlongitudeとかいう設定があるのだが、なんだろう?

とりあえず無視。




2012/12/20

2ちゃんねるでスクレイピングが失敗する

さくらのVPSサーバから、あるサイトにアクセスし、そのWEBサイトの情報の一部を取り出すという事をしている。いわゆる「スクレイピング」である。 

最初はperlで、LWP::Useragentなどを使って、あるサイトの情報を取り、あとは正規表現などを使って試行錯誤しつつ欲しい情報のみを取り出した。 特に難しいことはない。

ところが、同じ事を2ちゃんねるでやってみたら、うまくいかない。やろうとしたのは、ニュース速報の上位のスレッドタイトルを取得することだった。 2ちゃんねるは掲示板のメニューがあってそこに各掲示板のURLが記載されている。そしてその掲示板のURLはかなり頻繁に変更されるので、そのときアクセスできているURLに固定でアクセスせずに、メニューからURLを取得しなければならない。 その、メニューからURLを取得することはできたのだが、そこから取得したURLへアクセスすると、どうしてもHTMLの内容が取得できないのだ。

まずは、「302 Found」というエラーになる。これはリダイレクトされたときに出るもののようで、あるところで

push @{ $ua->requests_redirectable }, 'POST';
をやればいいという情報を見つけたのでやってみたら、今度は「ボボンハウス」のページが表示されてしまう。

同じperlスクリプトをローカルPCで動かしても同じ状況になる。 もちろん、ブラウザやギコナビなどでは問題なくアクセスできている。 昨日はここまでやって、あきらめて寝た。 

そして今日、perlのスクリプトでアクセスしたときと、ブラウザでアクセスしたときのパケットをwiresharkでキャプチャして比較してみた。

すると、GETしているときに、・・・・ と、ここまで書いてuseragentが違うことに気づいた。 perlで書いたものは何も設定しておらず、lwpの初期値が入っている。 これを'Mozilla'に変えたら・・・いけた。

昨日、変えてダメだったような記憶があったんだけどな・・・ ま、いいや。 これだけでいけるようになるということは、2ちゃんねるの「スクリプトキディ」除けかな。

今日はWEBでphpをつかったスクレイピング例を見つけてそれがうまく動いたのでそれをいじっていた。

しかし今度はphpの動作で不可解なところがでてきた。 まず、phpをcgiとして動かすために必要な設定がなんなのか。 いろいろと情報があるのだが、皆条件付でスパっと「ここをこうする!」という情報がない。

これも試行錯誤で試して、なんとかうごいた。 前回はこんなに苦労した記憶はないのに・・・。 さらに、いちおう動いたのだが、出力する内容が全部そのまま出てしまう。 htmlのリンクとかを書いても、そのまま表示されてリンクにならないのだ? なんでだ? 

話は変わるが、正規表現であるパターンにマッチする文字列が複数あり、それをすべて取り出したいときにはどうすればいいのだろう? たとえば、今まさにやりたかったのは、httpでgetしたデータの中にあるリンク(a href) を全部取り出して配列に格納する、というようなケースだ。 パッと思いつかず、サラっと探しても見つからなかったので、a hrefの前で改行してファイルに吐き出し、そのファイルを読んで一行ずつ処理するというメンドクサイことをしている。 こんなことしなくてもできるよね・・・。

2011/03/20

指定したユーザーの最新のツイートを30件表示する

指定したユーザーの最新のツイートを30件表示する。PHP。perlの例は少ないので。

$num_of_tweets = 30;
$user_name = "your_name";

$contents = file_get_contents('http://search.twitter.com/search.atom?q=from:'.$user_name.'&rpp='.$num_of_tweets);

$xml = simplexml_load_string($contents);

print '

'.$user_name.'

'; print '
'; for ($i = 0; $i < $num_of_tweets; $i++ ) { $tweet = $xml->entry[$i]->title; $tweet = mb_convert_encoding($tweet,"SJIS","UTF-8"); $date_tweeted = $xml->entry[$i]->published; $date_tweeted = date('Y/m/d H:i:s',strtotime($date_tweeted)); print $tweet.' ('.$date_tweeted.')

'; } print '
';


件数を100件にしたが、うまくいかなかった。

phpでoauthを使う場合の定番とされているものがあるようだ。

https://github.com/abraham/twitteroauth

OAuth.php

twitteroauth.php

この二つのファイルをダウンロードしておく。

下記がサンプル。上記二つのファイルはこのスクリプト自体と同じ場所においておく。

require_once('twitteroauth.php');

$consumer_key = 'xxxxxxxxxxxxxxx';
$consumer_secret = 'xxxxxxxxxxxxxxxxx';
$oauth_token = 'xxxxxxxxxxxxxxxxxxxx';
$oauth_secret = 'xxxxxxxxxxxxxxxxxxxxx';

$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_secret);
$content = $connection->get('account/verify_credentials');

$connection->post('statuses/update', array('status' => date(DATE_RFC822)));

実行しても何も表示されないが、twitterの自分のページを見ると、日付と時刻がtweetされているだろう。

今は自分のアプリケーションで自分のアカウントでツイートしているから、スクリプトに自分のconsumer key/secret, oauth token/secretを書き込んでいるが、実際には oauth token/secretは、利用者のそれを取得する必要がある。そのやり方も公開している人がいて、今ためしたらoauthによる認証まではできているようなのだが、肝心のそのあとのAPI操作ができない・・・

session_start();
require_once('twitteroauth.php');

$consumer_key = 'xxxxxxxxxx';
$consumer_secret = 'xxxxxxxxxxxxxxx';
$state = $_SESSION['oauth_state'];
$session_token = $_SESSION['oauth_request_token'];
$oauth_token = $_REQUEST['oauth_token'];
$section = $_REQUEST['section'];

if ($_REQUEST['test'] === 'clear') {
    session_destroy();
    session_start();
}

if ($_REQUEST['oauth_token'] != NULL && $_SESSION['oauth_state'] === 'start') {
    $_SESSION['oauth_state'] = $state = 'returned';
}

switch ($state) {
    default:
        $to = new TwitterOAuth($consumer_key, $consumer_secret);
        $tok = $to->getRequestToken();

        $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
        $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
        $_SESSION['oauth_state'] = "start";

        $request_link = $to->getAuthorizeURL($token);

        $content = 'Click on the link to go to twitter to authorize your account.';
        $content .= '
'.$request_link.''; //(A) $req = $to->OAuthRequest("https://twitter.com/statuses/update.xml","POST",array("status"=>"test")); header("Location: $request_link"); break; case 'returned': if ($_SESSION['oauth_access_token'] === NULL && $_SESSION['oauth_access_token_secret'] === NULL) { $to = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_request_token'],$_SESSION['oauth_request_token_secret']); $tok = $to->getAccessToken(); $_SESSION['oauth_access_token'] = $tok['oauth_token']; $_SESSION['oauth_access_token_secret'] = $tok['oauth_token_secret']; //(B) $req = $to->OAuthRequest("https://twitter.com/statuses/update.xml","POST",array("status"=>"test")); } $_SESSION['username'] = $tok["screen_name"]; //(C) $req = $to->OAuthRequest("https://twitter.com/statuses/update.xml","POST",array("status"=>"test")); header("Location: /"); }


最初は(C)のところだろうと書いてみたが、internal server errorになる。

(A),(B)に書いてみるとエラーにならないがtweetもされない。