PHPackages                             iamirnet/twitter-api-v2-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. iamirnet/twitter-api-v2-php

ActiveLibrary[API Development](/categories/api)

iamirnet/twitter-api-v2-php
===========================

This library provides methods for sending messages to Twitter and receiving statuses.

1.0.0(1y ago)07MITPHPPHP &gt;=7.4

Since Nov 30Pushed 1y agoCompare

[ Source](https://github.com/iamirnet/twitter-api-v2-php)[ Packagist](https://packagist.org/packages/iamirnet/twitter-api-v2-php)[ RSS](/packages/iamirnet-twitter-api-v2-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

Twitter API V2 for PHP
======================

[](#twitter-api-v2-for-php)

[![PHP](https://camo.githubusercontent.com/3161c23c32a872a0fdaf391770dc4081381e84f7ec2abfb7b7f949164e3ed728/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d76372e342b2d3832386362372e7376673f7374796c653d666c61742d737175617265266c6f676f3d706870)](https://camo.githubusercontent.com/3161c23c32a872a0fdaf391770dc4081381e84f7ec2abfb7b7f949164e3ed728/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d76372e342b2d3832386362372e7376673f7374796c653d666c61742d737175617265266c6f676f3d706870)[![Badge Twitter](https://camo.githubusercontent.com/43367c0cc353cf08fd31626b0c953de443fa8d512657ac901adf4c950c501f09/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f547769747465722532304150492d76322d3832386362372e7376673f7374796c653d666c61742d737175617265266c6f676f3d7477697474657226636f6c6f723d314441314632)](https://developer.twitter.com/en/docs/twitter-api)[![Run Tests](https://github.com/iamirnet/twitter-api-v2-php/actions/workflows/run-tests.yml/badge.svg)](https://github.com/iamirnet/twitter-api-v2-php/actions/workflows/run-tests.yml)[![MIT Licensed](https://camo.githubusercontent.com/94b13cd1065c4a0b3b27eaea95858af5368679595cf7b795880b09ada634c786/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f69616d69726e65742f747769747465722d6170692d76322d706870)](licence.md)[![last version](https://camo.githubusercontent.com/becf97c1131cc299375f96c67a9ff3dd7844abdeb153adbb437457cbb4029f61/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69616d69726e65742f747769747465722d6170692d76322d706870)](https://packagist.org/packages/iamirnet/twitter-api-v2-php)[![Downloads](https://camo.githubusercontent.com/82032e1623c4dacc4bb58d48faad9f3c0988def10a71890a5fff491f684c7c77/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f69616d69726e65742f747769747465722d6170692d76322d706870)](https://packagist.org/packages/iamirnet/twitter-api-v2-php)[![twitter](https://camo.githubusercontent.com/c4ba5c35c38618c4badc7f43c8e61a6ba37319d1b205820f018345c53a7fc375/68747470733a2f2f696d672e736869656c64732e696f2f747769747465722f666f6c6c6f772f4e6f7765684a533f7374796c653d736f6369616c)](https://x.com/NowehJS)

Twitter API V2 is a PHP package which provides an easy and fast access to Twitter REST API for Version 2 endpoints.

Documentation
-------------

[](#documentation)

- [Installation](#installation)
- [Github Actions](#github-actions)
- [Usage](#usage)
    - [Active your developer account](#active-your-developer-account)
    - [Configuration setup](#configuration-setup)
    - [API Functionality](#api-functionality)
        - [Include the HTTP headers provided by Twitter in the response](#include-the-http-headers-provided-by-twitter-in-the-response)
- [Tweets endpoints](#tweet-endpoints)
    - [Timeline endpoints](#timeline-endpoints)
        - [Find Recent Mentioning for a User](#find-recent-mentioning-for-a-user)
        - [Find Recent Tweets for a User](#find-recent-tweets-for-a-user)
        - [Reverse Chronological Timeline by user ID](#reverse-chronological-timeline-by-user-id)
    - [Tweet/Likes endpoints](#tweetlikes-endpoints)
        - [Tweets liked by a user](#tweets-liked-by-a-user)
        - [Users who liked a tweet](#users-who-liked-a-tweet)
    - [Tweet/Lookup endpoints](#tweetlikes-endpoints)
        - [Search specific tweets](#search-specific-tweets)
        - [Find all replies from a Tweet](#find-all-replies-from-a-tweet)
    - [Tweet endpoints](#tweetlikes-endpoints)
        - [Fetch a tweet by Id](#fetch-a-tweet-by-id)
        - [Create a new Tweet](#create-a-new-tweet)
        - [Upload image to Twitter (and use in Tweets)](#upload-image-to-twitter-and-use-in-tweets)
    - [Tweet/Quotes endpoints](#tweetquotes-endpoints)
        - [Returns Quote Tweets for a Tweet specified by the requested Tweet ID](#returns-quote-tweets-for-a-tweet-specified-by-the-requested-tweet-id)
    - [Retweet endpoints](#retweet-endpoints)
        - [Retweet a Tweet](#retweet-a-tweet)
    - [Tweet/Replies endpoints](#tweetreplies-endpoints)
        - [Hide a reply to a Tweet](#hide-a-reply-to-a-tweet)
        - [Unhide a reply to a Tweet](#unhide-a-reply-to-a-tweet)
    - [Tweet/Bookmarks endpoints](#tweetbookmarks-endpoints)
        - [Lookup a user's Bookmarks](#lookup-a-users-bookmarks)
- [Users endpoints](#users-endpoints)
    - [User/Blocks endpoints](#userblocks-endpoints)
        - [Retrieve the users which you've blocked](#retrieve-the-users-which-youve-blocked)
    - [User/Follows endpoints](#userfollows-endpoints)
        - [Retrieve the users which are following you](#retrieve-the-users-which-are-following-you)
        - [Retrieve the users which you are following](#retrieve-the-users-which-you-are-following)
        - [Follow a user](#follow-a-user)
        - [Unfollow a user](#unfollow-a-user)
    - [User/Lookup endpoints](#userlookup-endpoints)
        - [Find me](#find-me)
        - [Find Twitter Users](#find-twitter-users)
    - [User/Mutes endpoints](#usermutes-endpoints)
        - [Retrieve the users which you've muted](#retrieve-the-users-which-youve-muted)
        - [Mute user by username or ID](#mute-user-by-username-or-id)
        - [Unmute user by username or ID](#unmute-user-by-username-or-id)
- [Contributing](#contributing)
    - [To run test](#to-run-tests)
    - [To run code analyzer](#to-run-code-analyzer)

Installation
------------

[](#installation)

To begin, you'll need to add the component to your `composer.json`

```
composer require iamirnet/twitter-api-v2-php
```

After adding the component, update your packages using `composer update` or install them using `composer install`.

Github Actions
--------------

[](#github-actions)

This repository uses [Github Actions](https://github.com/iamirnet/twitter-api-v2-php/actions) for each push/pull request, employing [PHPStan/PHPUnit](/.github/workflows/run-tests.yml).

Consequently, with each valid push, a new Tweet is posted from the [Twitter test account](https://twitter.com/canWeDeploy/status/1538477133487644672).

Usage
-----

[](#usage)

### Active your developer account

[](#active-your-developer-account)

Before anything else, you must follow [this tutorial](https://developer.twitter.com/en/docs/tutorials/getting-started-with-r-and-v2-of-the-twitter-api).

- [Request approval for a developer account](https://developer.twitter.com/en/apply-for-access);
- Once your developer account is approved, you will need to [create a Project](https://developer.twitter.com/en/docs/projects/overview);
- Enable read/write access for your Twitter app;
- Generate Consumer Keys and Authentication Tokens;
- Retrieve your Keys and Tokens from the Twitter Developer portal.

### Configuration setup

[](#configuration-setup)

Expected settings are as follows:

```
use Noweh\TwitterApi\Client;

$settings = [
    'account_id' => 'YOUR_ACCOUNT_ID',
    'access_token' => 'YOUR_ACCESS_TOKEN',
    'access_token_secret' => 'YOUR_TOKEN_SECRET',
    'consumer_key' => 'YOUR_CONSUMER_KEY',
    'consumer_secret' => 'YOUR_CONSUMER_SECRET',
    'bearer_token' => 'YOUR_BEARER_TOKEN',
    'free_mode' => false, // Optional
    'api_base_uri' => 'https://api.twitter.com/2/', // Optional
];

$client = new Client($settings);
```

By changing the value of `'api_base_uri'` you can have the requests target a different server, for instance, a simulated one, thus making testing your application in isolation easier.

For a quick mock server setup you can use [mockoon](https://mockoon.com/).

### API Functionality

[](#api-functionality)

All API calls are triggered when the `performRequest()` method is invoked. Depending on the context, this method can either be empty or contain data that will be sent as PostData (refer to examples of each call below).

#### Include the HTTP headers provided by Twitter in the response

[](#include-the-http-headers-provided-by-twitter-in-the-response)

The `performRequest()` method accepts a second parameter, `$withHeaders`, which is a boolean value. Setting this parameter to `true` will include the headers information in the response.

Here are some examples of information included in headers:

- `x-rate-limit-limit`: the rate limit ceiling for that given endpoint
- `x-rate-limit-remaining`: the number of requests left for the 15-minute window
- `x-rate-limit-reset`: the remaining window before the rate limit resets, in UTC epoch seconds

Example:

```
$response = $this->client->tweet()->create()
    ->performRequest([
        'text' => 'Test Tweet... '
    ],
    withHeaders: true)
;

/*
Output:
object(stdClass)#399 (2) {
    ["data"]=>
    object(stdClass)#398 (3) {
        ["edit_history_tweet_ids"]=>
        array(1) {
            [0]=>
            string(19) "1690304934837637121"
        }
        ["id"]=>
        string(19) "1690304934837637121"
        ["text"]=>
        string(39) "Test Tweet..."
    }
    ["headers"]=>
        ...
        ["x-rate-limit-limit"]=>
        array(1) {
            [0]=>
            string(5) "40000"
        }
        ["x-rate-limit-reset"]=>
        array(1) {
            [0]=>
            string(10) "1691835953"
        }
        ["x-rate-limit-remaining"]=>
        array(1) {
            [0]=>
            string(5) "39998"
        }
        ...
    }
}
*/
```

### Free mode

[](#free-mode)

This API can be used in free mode, which allows for a limited usage of the API. In this mode, the [Find me](#find-me) method is the only one that can be used. You have to set the `free_mode` parameter to `true` when creating the client.

Example:

```
...
$settings['free_mode'] = true;
$client = new Client($settings);
```

---

Tweets endpoints
----------------

[](#tweets-endpoints)

Timeline endpoints
------------------

[](#timeline-endpoints)

### Find Recent Mentioning for a User

[](#find-recent-mentioning-for-a-user)

Example:

```
$return = $client->timeline()->getRecentMentions($accountId)->performRequest();
```

### Find Recent Tweets for a User

[](#find-recent-tweets-for-a-user)

Example:

```
$return = $client->timeline()->getRecentTweets($accountId)->performRequest();
```

### Reverse Chronological Timeline by user ID

[](#reverse-chronological-timeline-by-user-id)

Example:

```
$return = $client->timeline()->getReverseChronological()->performRequest();
```

Tweet/Likes endpoints
---------------------

[](#tweetlikes-endpoints)

### Tweets liked by a user

[](#tweets-liked-by-a-user)

Example:

```
$return = $client->tweetLikes()->addMaxResults($pageSize)->getLikedTweets($accountId)->performRequest();
```

### Users who liked a tweet

[](#users-who-liked-a-tweet)

Example:

```
$return = $client->tweetLikes()->addMaxResults($pageSize)->getUsersWhoLiked($tweetId)->performRequest();
```

Tweet/Lookup endpoints
----------------------

[](#tweetlookup-endpoints)

### Search specific tweets

[](#search-specific-tweets)

Example:

```
$return = $client->tweetLookup()
    ->showMetrics()
    ->onlyWithMedias()
    ->addFilterOnUsernamesFrom([
        'twitterdev',
        'Noweh95'
    ], \Noweh\TwitterApi\TweetLookup::OPERATORS['OR'])
    ->addFilterOnKeywordOrPhrase([
        'Dune',
        'DenisVilleneuve'
    ], \Noweh\TwitterApi\TweetLookup::OPERATORS['AND'])
    ->addFilterOnLocales(['fr', 'en'])
    ->showUserDetails()
    ->performRequest()
;

$client->tweetLookup()
    ->addMaxResults($pageSize)
    ->addFilterOnKeywordOrPhrase($keywordFilter)
    ->addFilterOnLocales($localeFilter)
    ->showUserDetails()
    ->showMetrics()
    ->performRequest()
;
```

### Find all replies from a Tweet

[](#find-all-replies-from-a-tweet)

```
->addFilterOnConversationId($tweetId);
```

Tweet endpoints
---------------

[](#tweet-endpoints)

### Fetch a tweet by Id

[](#fetch-a-tweet-by-id)

Example:

```
$return = $client->tweet()->->fetch(1622477565565739010)->performRequest();
```

### Create a new Tweet

[](#create-a-new-tweet)

Example:

```
$return = $client->tweet()->create()->performRequest(['text' => 'Test Tweet... ']);
```

### Upload image to Twitter (and use in Tweets)

[](#upload-image-to-twitter-and-use-in-tweets)

Example:

```
$file_data = base64_encode(file_get_contents($file));
$media_info = $client->uploadMedia()->upload($file_data);
$return = $client->tweet()->create()
    ->performRequest([
        'text' => 'Test Tweet... ',
        "media" => [
            "media_ids" => [
                (string)$media_info["media_id"]
            ]
        ]
    ])
;
```

Tweet/Quotes endpoints
----------------------

[](#tweetquotes-endpoints)

### Returns Quote Tweets for a Tweet specified by the requested Tweet ID

[](#returns-quote-tweets-for-a-tweet-specified-by-the-requested-tweet-id)

Example:

```
$return = $client->tweetQuotes()->getQuoteTweets($tweetId)->performRequest();
```

Retweet endpoints
-----------------

[](#retweet-endpoints)

### Retweet a Tweet

[](#retweet-a-tweet)

Example:

```
$return = $client->retweet()->performRequest(['tweet_id' => $tweet_id]);
```

Tweet/Replies endpoints
-----------------------

[](#tweetreplies-endpoints)

### Hide a reply to a Tweet

[](#hide-a-reply-to-a-tweet)

Example:

```
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => true]);
```

### Unhide a reply to a Tweet

[](#unhide-a-reply-to-a-tweet)

Example:

```
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => false]);
```

Tweet/Bookmarks endpoints
-------------------------

[](#tweetbookmarks-endpoints)

### Lookup a user's Bookmarks

[](#lookup-a-users-bookmarks)

Example:

```
$return = $client->tweetBookmarks()->lookup()->performRequest();
```

---

Users endpoints
---------------

[](#users-endpoints)

User/Blocks endpoints
---------------------

[](#userblocks-endpoints)

### Retrieve the users which you've blocked

[](#retrieve-the-users-which-youve-blocked)

Example:

```
$return = $client->userBlocks()->lookup()->performRequest();
```

User/Follows endpoints
----------------------

[](#userfollows-endpoints)

### Retrieve the users which are following you

[](#retrieve-the-users-which-are-following-you)

Example:

```
$return = $client->userFollows()->getFollowers()->performRequest();
```

### Retrieve the users which you are following

[](#retrieve-the-users-which-you-are-following)

Example:

```
$return = $client->userFollows()->getFollowing()->performRequest();
```

### Follow a user

[](#follow-a-user)

Example:

```
$return = $client->userFollows()->follow()->performRequest(['target_user_id' => $userId]);
```

### Unfollow a user

[](#unfollow-a-user)

Example:

```
$return = $client->userFollows()->unfollow($userId)->performRequest(['target_user_id' => self::$userId]);
```

User/Lookup endpoints
---------------------

[](#userlookup-endpoints)

### Find Me

[](#find-me)

Example:

```
$return = $client->userMeLookup()->performRequest();
```

### Find Twitter Users

[](#find-twitter-users)

`findByIdOrUsername()` expects either an array, or a string.

You can specify the search mode as a second parameter (`Client::MODES['USERNAME']` OR `Client::MODES['ID']`)

Example:

```
$return = $client->userLookup()
    ->findByIdOrUsername('twitterdev', \Noweh\TwitterApi\UserLookup::MODES['USERNAME'])
    ->performRequest()
;
```

User/Mutes endpoints
--------------------

[](#usermutes-endpoints)

### Retrieve the users which you've muted

[](#retrieve-the-users-which-youve-muted)

Example:

```
$return = $client->userMutes()->lookup()->performRequest();
```

### Mute user by username or ID

[](#mute-user-by-username-or-id)

Example:

```
$return = $client->userMutes()->mute()->performRequest(['target_user_id' => $userId]);
```

### Unmute user by username or ID

[](#unmute-user-by-username-or-id)

Example:

```
$return = $client->userMutes()->unmute()->performRequest(['target_user_id' => $userId]);
```

---

Contributing
------------

[](#contributing)

Fork/download the code and run

```
composer install
```

copy `test/config/.env.example` to `test/config/.env` and add your credentials for testing.

### To run tests

[](#to-run-tests)

```
./vendor/bin/phpunit
```

### To run code analyzer

[](#to-run-code-analyzer)

```
./vendor/bin/phpstan analyse .
```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 56.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

535d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1670938?v=4)[Peyman Jahani](/maintainers/jahani)[@jahani](https://github.com/jahani)

---

Top Contributors

[![noweh](https://avatars.githubusercontent.com/u/11422029?v=4)](https://github.com/noweh "noweh (63 commits)")[![syslogic](https://avatars.githubusercontent.com/u/736481?v=4)](https://github.com/syslogic "syslogic (38 commits)")[![cibles](https://avatars.githubusercontent.com/u/19661971?v=4)](https://github.com/cibles "cibles (3 commits)")[![vangelier-visma](https://avatars.githubusercontent.com/u/124263173?v=4)](https://github.com/vangelier-visma "vangelier-visma (3 commits)")[![iamirnet](https://avatars.githubusercontent.com/u/68027783?v=4)](https://github.com/iamirnet "iamirnet (2 commits)")[![mchojrin](https://avatars.githubusercontent.com/u/1532615?v=4)](https://github.com/mchojrin "mchojrin (2 commits)")

---

Tags

phpapitwitter

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/iamirnet-twitter-api-v2-php/health.svg)

```
[![Health](https://phpackages.com/badges/iamirnet-twitter-api-v2-php/health.svg)](https://phpackages.com/packages/iamirnet-twitter-api-v2-php)
```

###  Alternatives

[openai-php/laravel

OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with the Open AI API

3.7k7.6M74](/packages/openai-php-laravel)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.5k311.5k5](/packages/theodo-group-llphant)[noweh/twitter-api-v2-php

This library provides methods for sending messages to Twitter and receiving statuses.

131225.2k1](/packages/noweh-twitter-api-v2-php)[fennb/phirehose

A PHP interface to the Twitter Streaming API.

698402.4k3](/packages/fennb-phirehose)[resend/resend-php

Resend PHP library.

574.7M21](/packages/resend-resend-php)[redwebcreation/twitter-stream-api

Consume the Twitter Stream API in real-time.

3220.3k1](/packages/redwebcreation-twitter-stream-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
