Mastodon is a decentralized, open-source, federated social network that provides an ethical alternative to traditional social media platforms. Unlike Twitter or Facebook, Mastodon is not controlled by a single central entity.
Mastodon’s decentralization is based on the concept of interconnected instances (or servers). Each instance is independently managed, with its own rules and community, while allowing users to interact with members of other instances. This architecture, built on the ActivityPub protocol, forms what is known as the “Fediverse” – a truly distributed social network.
The benefits of this decentralized approach include:
- No ads or user tracking
- Greater control over personal data
- More effective and localized moderation adapted to each community
- Resistance to censorship due to network distribution
Now that we’ve introduced the Mastodon network, let’s learn how to publish a post on Mastodon using PHP.
Prerequisites
First, you need an account on a Mastodon instance. In my case, I use the instance piaille.fr
.
You also need to obtain an access token.
Here’s how:
- Log in to your Mastodon instance.
- Go to the “Preferences” page.
- Navigate to the “Development” menu.
- Click on the “New application” button.
- Set the application name: in our case, we’ll call it “MastoBot.”
- Check the
write:media
andwrite:statuses
scopes. - Save your settings; you’ll arrive at the list of applications.
- Click on your application.
- Retrieve your access token.
Theory
We will use the Mastodon API, which is documented online.
If you wish to use images, you first need to upload the media via the POST /api/v2/media
endpoint. The response will return media identifiers (id
) that you can use when creating the status (media_ids[]
).
Implementation
The implementation will be done in PHP 8.4 with the Curl extension installed and enabled.
|
|
As you can see in the code, no library is used, and we work directly with Curl, which keeps the code simple.
The returned response is also documented in the Mastodon documentation.
After running the code, you will notice:
- The application name is displayed in the bottom right corner.
- You can also use emojis.