Check if twitter username exists

2019-02-04 18:29发布

Is there a way to check if a twitter username exists? Without being authenticated with OAuth or the twitter basic authentication?

9条回答
霸刀☆藐视天下
2楼-- · 2019-02-04 19:01

As API v1 is no longer available, here is another way to check if a twitter account exists. The page headers of a non existing account contain 404 (page not found).

function twitterAccountExists($username){
    $headers = get_headers("https://twitter.com/".$username);
    if(strpos($headers[0], '404') !== false ) {
        return false;
    } else {
        return true;
    }
}
查看更多
SAY GOODBYE
3楼-- · 2019-02-04 19:09

This worked for me, close to what sferik has posted.

def twitter_user_exists?(user)
   Twitter.user(user)
   true
rescue Twitter::Error::NotFound
   false
end
查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-04 19:12

According to the api docs you can pass an email address to the user/ show method, I would assume that if a user didn't exist you'd get back a 404, which should allow you to determine whether or not the user exists.

eg: http://twitter.com/users/show.xml?email=t...@example.com

result if not exist :

<?xml version="1.0" encoding="UTF-8"?> 
<hash> 
  <request>/users/show.xml?email=tur...@example.com</request> 
  <error>Not found</error> 
</hash
查看更多
戒情不戒烟
5楼-- · 2019-02-04 19:17

You can also use the API with username :

eg : http://api.twitter.com/1/users/show.xml?screen_name=tarnfeld

Will give you :

<?xml version="1.0" encoding="UTF-8"?>
<user>
  ...................
  <screen_name>tarnfeld</screen_name>
  <location>Portsmouth, UK</location>
  .................
  </status>
</user>

Or if not exist :

<?xml version="1.0" encoding="UTF-8"?>
<hash>
  <request>/1/users/show.xml?screen_name=tarnfeldezf</request>
  <error>Not found</error>
</hash>
查看更多
走好不送
6楼-- · 2019-02-04 19:17

Using Ruby, you could install the twitter gem and then define the following method:

require 'twitter'

def user_exists?(user)
  Twitter.user(user)
  true
rescue Twitter::NotFound
  false
end

Then, simply pass in a Twitter user name or id to your method, like so:

user_exists?("sferik") #=> true
user_exists?(7505382) #=> true
查看更多
一夜七次
7楼-- · 2019-02-04 19:18

Here is how it works on PHP :

$user_infos = 'http://api.twitter.com/1/users/show.xml?screen_name='.$username;

if (!@fopen($user_infos, 'r'))
{
return false;
}
return true;
查看更多
登录 后发表回答