Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active December 22, 2022 16:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adactio/c3652f2241c29bdc5af116bb02594d61 to your computer and use it in GitHub Desktop.
Save adactio/c3652f2241c29bdc5af116bb02594d61 to your computer and use it in GitHub Desktop.
A PHP function that posts an update to Mastodon
<?php
/*
Pass in an array of data with keys for `status`
e.g.
postToMastodon(array(
'status' => 'Hello, world!'
));
Include `reply_url` if you're responding to a post
e.g.
postToMastodon(array(
'status' => 'Hello, Jeremy!',
'reply_url' => 'https://mastodon.social/@adactio/109343712638768951'
));
*/
function postToMastodon($data=array()) {
// Get your access token from /settings/applications in your Mastodon instance.
$accessToken = 'XXXXXXXXXXXX';
// Swap out mastodon.social for your Mastodon instance
$url = 'https://mastodon.social/api/v1/statuses';
$fields['status'] = $data['status'];
if (isset($data['reply_url'])) {
if (stristr($data['reply_url'], '/@')) {
$urlparts = parse_url($data['reply_url']);
$pathparts = explode('/', $urlparts['path']);
$toot_id = $pathparts[2];
$fields['in_reply_to_id'] = $toot_id;
$username = $pathparts[1];
$fields['status'] = $username.' '.$fields['status'];
}
}
$headers = array(
"Authorization: Bearer ".$accessToken,
"Content-Type: application/json",
"Accept: application/json",
"Accept-Charset: utf-8"
);
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => json_encode($fields),
CURLOPT_TIMEOUT => 20
);
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
?>
@adactio
Copy link
Author

adactio commented Nov 17, 2022

Referenced in this blog post: Syndicating to Mastodon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment