the Website of Timothy McCabe Follower of Christ; Student of Epistemology, Apologetics, and Theology
Home Good News Proofs Questions Presentations Software More

Post a tweet to the X API in PHP without any special libraries

December 6, 2024

I really dislike using third-party libraries. Often I find that they are far, far more trouble than they're worth. But even when they really provide some value, they're often a square-peg/round-hole problem; a one-size-fits-all solution that doesn't really fit any problem very well. They make debugging more difficult by adding another untouchable, black-box codebase that could be broken, a codebase that you can't fix even if your own customers need it to work. Anyway, for me, vanilla is best almost all the time.

In the case of posting to the X API, the amount of vanilla code you need is pretty small, so why on earth would anyone waste their time trying to learn and import a library to "help"? And yet people do. Lots of them. I suspect this is because Tw... X's documentation is awful, and everything I found on Stack Overflow was outdated, or partial, or incorrect. Regardless, here's some December, 2024 vanilla PHP code you can copy verbatim and use to automatically post to the X API, along with correlations for the weird variable naming that X employs to make things really clear.

A.I. agrees that human reason necessitates God
Artificial Intelligence chatbot Claude agrees that the existence of human reason can only be explained by the existence of an omnipotent, omniscient, rational God.

Other than filling in the four initial variables with your own data, data that X will give you in your project's control panel, you should be able to keep the rest of the code exactly as-is. But do make sure that your project has read-write access (in your online X developer dashboard, under App Settings > User Authentication Settings > Edit), and not just read access (the default).

<?php
 
function postTweet($tweetString)
{
    // Fill in the following four variables according
    // to the data X gives you in your
    // project control panel.
 
    // X calls this your "API Key"
    $key = '';
    // X calls this your "Access Token"
    $token = '';
    // X calls this your "API Key Secret"
    $consumerSecret = '';
    // X calls this your "Access Token Secret"
    $tokenSecret = '';
 
    // Make sure these variables are percent-encoded
    // https://developer.x.com/en/docs/authentication/oauth-1-0a/authorizing-a-request
    $consumerSecret = rawurlencode($consumerSecret);
    $tokenSecret = rawurlencode($tokenSecret);
 
    // Define some other variables
    // https://developer.x.com/en/docs/x-api/tweets/manage-tweets/api-reference/post-tweets
    $url = 'https://api.x.com/2/tweets';
    $nonce = dechex(microtime(true) * 1000).bin2hex(random_bytes(8));
    $timestamp = time();
    $fields = array("text" => $tweetString);
    $postvars = json_encode($fields);
 
    // Make the signature
    // https://developer.x.com/en/docs/authentication/oauth-1-0a/creating-a-signature
    $parameters = 'POST&'.rawurlencode($url).'&'.rawurlencode(join("",
    [
        'oauth_consumer_key='.rawurlencode($key),
        '&oauth_nonce='.rawurlencode($nonce),
        '&oauth_signature_method='.rawurlencode('HMAC-SHA1'),
        '&oauth_timestamp='.rawurlencode($timestamp),
        '&oauth_token='.rawurlencode($token),
        '&oauth_version='.rawurlencode('1.0'),
    ]));
 
    // Encrypt the signature
    $signingKey = $consumerSecret.'&'.$tokenSecret;
    $hashedSignature = hash_hmac('sha1', $parameters, $signingKey, true);
    $signature = base64_encode($hashedSignature);
 
    // Create your oauth string
    // https://developer.x.com/en/docs/authentication/oauth-1-0a
    $oauth = join(", ",
    [
        'oauth_consumer_key="'.rawurlencode($key).'"',
        'oauth_nonce="'.rawurlencode($nonce).'"',
        'oauth_signature_method="'.rawurlencode('HMAC-SHA1').'"',
        'oauth_timestamp="'.rawurlencode($timestamp).'"',
        'oauth_token="'.rawurlencode($token).'"',
        'oauth_version="'.rawurlencode('1.0').'"',
        'oauth_signature="'.rawurlencode($signature).'"',
    ]);
 
    // Open the connection
    $ch = curl_init();
    // Set the url, POST data, etc
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 0);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-type: application/json',
        'Authorization: OAuth '.$oauth
    ));
 
    // Call X
    $resultstr = curl_exec($ch);
    // Close connection
    curl_close($ch);
    // Display the results
    echo('<p>'.$resultstr.'</p>');
}
 
// Launch it like this:
postTweet('Posted via the API! #HelloWorld https://presuppositions.org/software/php-post-tweet-x-api');
 
?>

That should be it. If something doesn't seem to work right, please let me know.

Gilbert Guttlebocker, Defender of Dragons

Gilbert Guttlebocker, Defender of Dragons

Riveting, yet absurd; romantic, yet innocent; Gilbert Guttlebocker, Defender of Dragons is a little Roald Dahl, a little Harry Potter, and a little Chronicles of Narnia, all rolled into one. Timothy McCabe collaborates with the great Benedict Ballyhoot to bring you the novel of the century!

 

World Religions and Cults (volume 2)

In Printed Form

Along with numerous other authors including Don Landis, Bodie Hodge and Roger Patterson, Timothy McCabe contributes analyses of various world religions and cults in this volume from Master Books.

Other Writings

"Does the "problem of evil" show that an all-good, all-powerful, all-knowing god cannot exist?"

The "problem of evil" generally goes something like this. 1. If God had all-power over our universe, he would have been able to prevent the wickedness of Adolf Hitler. 2. If God had all-knowledge of our universe, he would have known how to prevent the wickedness of Adolf Hitler. 3. If God were morally good, he would have wanted to prevent the wickedness of Adolf Hitler. 4. Adolf Hitler was wicked in our universe. 5.
Continue reading...

"If everything was created by God, was Buddha also created by God? Buddha actually denied the existence of a single being that dominates/governs the whole world. Did Buddha go to hell for denying his existence?"

Siddhartha Gautama, or Buddha, was created by God, yes. Everyone who is not God was created by God (Genesis 1:27; Ecclesiastes 7:29; Isaiah 46:9), and God cannot lie (Titus 1:2; Hebrews 6:18), and is never wrong (Colossians 2:3; John 21:17; 1 John 3:20). If Buddha claimed there is no ultimate creator God, then either he was wrong or he was lying, thereby identifying himself as not-that-god, since God cannot lie and is never wrong.
Continue reading...

"How would you respond to Stephen Law's Evil God Challenge?"

Atheist Stephen Law challenges monotheists everywhere to explain "why the good god hypothesis should be considered significantly more reasonable than the evil god hypothesis". Most classical theistic arguments for the existence of God, Dr. Law claims, even if successful in proving an omnipotent and omniscient God, do nothing to speak to His moral character.
Continue reading...

All articles