Quick free auto-post-to-Twitter PHP script in the age of Elon Musk
Right, here’s a very quick and dirty blog post about how to achieve an auto-post to Twitter; because the documentation these days is hiding behind a lot of change after Elon Musk took over and ruined it. This works as of Sep 2023.
The Twitter side
Log into the Twitter Developer Portal
You need a project, and one (and only one) project app underneath that project. Don’t worry about setting up user authentication - you can’t use it.
In “keys and settings”, you want to get four bits - the API key and secret, the access token and secret.
You’re using the v2 API, where you can ONLY create a tweet, literally nothing else, and you get 500 tweets a day.
Your PHP code
From the PHP side, you want to install abraham/twitteroauth - but once you’ve installed it, ignore the documentation because it’s no longer right.
To post a tweet, use this PHP nonsense
use Abraham\TwitterOAuth\TwitterOAuth;
//connect with your tokens
$connection = new TwitterOAuth(
$config['twitter-consumer-key'],
$config['twitter-consumer-secret'],
$config['twitter-access-token'],
$config['twitter-access-token-secret']
);
//set the API version to v2 otherwise nothing will work
$connection->setApiVersion('2');
//prepare your tweet
$text="That @jamescridland wrote a quick script and I'm using it.";
//Post your tweet
$result = $connection->post("tweets", ["text" => $text], true);
//Test that it went
if ($connection->getLastHttpCode()<299) {
echo "BIG SUCCESS!";
} else {
echo "MASSIVE FAIL!";
print_r($connection);
}
And that really is it. You’ll get an ugly error if it fails with some information to help, possibly. You’ll want to catch that properly in production, right? Right.