Apr 142013

This article describes how to post messages to Google+ using PHP; I will use this method for my Social Media Cross-posting script.

In the first installment of this series of articles I explained why I want to read pictures from a tweet: because Google+ and Facebook show nice big pictures if uploaded to Google+ and Facebook; posting a link to a picture will result in a thumbnail.
The second article shows how to read tweets from twitter using PHP.
There is a nice way to find and download pictures that have been uploaded to PHP, it is described in the third artice of this series.

This article will show talk about the following subjects:

  • The (very limited) Google+ API
  • The alternative: NextScripts
  • Using the NextScripts solution
  • Prevent posting the same message again
  • Full code for this post

The (very limited) Google+ API

Even though Google+ already exists for many years, the provided API currently only allows you to read posts from public accounts – that’s it. Check out what Google says about the API, read the note below:

google+ api

So, we are on our own when it comes to automated posting to Google+.
There is always the option of ‘screen scraping’ – mimic a user who is posting a message from his browser. What you have to program to accomplish this is:

  • Fetch to the Google+ login page
  • Perform a submit with login credentials like a human would
  • Find out what post fields to fill when you want to post a message
  • Perform a submit with the correct fields; if you want to add a photo or a link, it will be a lot more complicated

It is possible that Google decides to change something to the login or post screens; then you will have to rewrite the screen scraping software because the software expects other fields or values.

I have written multiple applications with screen scraping technologies, and I don’t want to go that route again. Luckily, I found an alternative.

The alternative: NextScripts

The guys from NextScripts have written a library that does the dirty work of posting a message to Google+ – test drive it over here. I know, it is not a free script, but for $49 you buy a script with unlimited updates/upgrades. So whenever Google decides to change the login or posting screens, the programmers from NextScripts will update their script, I will download it and use it again for cross-posting tweets.

The script is very easy to use, here is a snippet that actually will post something to Google+:

  1. <?php
  2. require "postToGooglePlus.php";
  4. $email = 'YourEmail@gmail.com';
  5. $pass = 'YourPassword';
  6. $msg = 'Post this to Google Plus!';
  8. $loginError = doConnectToGooglePlus2($email, $pass);
  9. if (!$loginError)
  10.     doPostToGooglePlus2($msg);
  11. else
  12.     echo $loginError;
  13. ?>

That’s it! Posting a link or image is just as easy, add it as a parameter to doPostToGooglePlus2() as I will show you in the next chapter.

Using the NextScripts solution

Let’s incorporate this in our script from the previous blog. I will show you some snippets first, and the full script at the end of this article.

The NextScripts library must be included in our script; put the file postToGooglePlus.php in the lib directory, and add it to the list of includes:

  1. <?php
  3. include 'lib/EpiCurl.php';
  4. include 'lib/EpiOAuth.php';
  5. include 'lib/EpiTwitter.php';
  6. include 'lib/postToGooglePlus.php';
  7. include 'cfg/secret.php';

Add your Google+ login credentials in the cfg/secret.php file:

  1. $g_email         = 'your.google.account@gmail.com';
  2. $g_passwd        = 'your password';

Add a post function to our PHP code:

  1. function PostToGooglePlus($msg, $attach) {
  2.     global $g_email, $g_passwd;
  4.     $loginError = doConnectToGooglePlus2($g_email, $g_passwd);
  5.     if (!$loginError) {
  6.         if ($attach) {
  7.             # If we have an attachment, and it points to twimg.com, make it an image attachment
  8.            if (preg_match("/twimg.com/", $attach)) {
  9.                 $lnk = array('img'=>$attach);
  10.             } else {
  11.                 $lnk = doGetGoogleUrlInfo2($attach);
  12.             }
  13.             doPostToGooglePlus2($msg, $lnk);
  14.         } else {
  15.             doPostToGooglePlus2($msg);
  16.         }
  17.     } else {
  18.         echo $loginError;
  19.     }
  20. }

There is one thing I should explain about this code. On line 8, I try to figure out whether the attachment from the tweet is either a link to the Twitter image service; if it is (it matches twimg.com) then I have to tell the Google+ library that the link should be handled as an image attachment; otherwise the link will be prepared with a call to the function doGetGoogleUrlInfo2(), see line 11.
Once done, I can call the function doPostToGooglePlus2(), either with or without the link.

Prevent posting the same message again

The loop, as it is in the previous article, always shows the last 20 tweets; however, we want to cross-post each tweet only once. So we will have to remember the tweets that already have been cross-posted. I will show a database solution in the last article of this series, for now I will add the tweet ID to a file, and add a check in the loop.

Here is the code for the tweet loop (the full code is at the end of the article):

  1. $tweets_done = "cfg/tweets_done";
  2. foreach ($response as $tweet) {
  3.     # Find the tweet ID
  4.    $id = $tweet['id_str'];
  6.     # If the id is not in the $tweets_done, handle it
  7.    $in_file = 'grep $id $tweets_done';
  9.     if (!$in_file) {
  10.         # Get tweet text and possible attachment
  11.        list($tweet_text, $tweet_attach) = ReadTweet($tweet);
  13.         # Send it to Google+
  14.        PostToGooglePlus($tweet_text, $tweet_attach);
  16.         # Show the tweet and attachment
  17.        echo "$tweet_text\n";
  18.         if ($tweet_attach) echo "Attachment: $tweet_attach\n";
  19.         echo "\n";
  21.         # Add the tweet ID to the $tweets_done file
  22.        file_put_contents($tweets_done, "$id\n", FILE_APPEND);
  23.     }
  24. }

The file cfg/tweets_done will contain all ID’s of tweets that have been cross-posted.
If we find a tweet that is not in the file, the text and possible attachment are read from the tweet (line 11) and posted to Google+ (line 14). Don’t forget to save this tweet ID in the id-file (line 22).

Full code for this post

Here is the full listing; for the contents of the lib and cfg directory, refer to the previous posts of this series.

  1. <?php
  3. include 'lib/EpiCurl.php';
  4. include 'lib/EpiOAuth.php';
  5. include 'lib/EpiTwitter.php';
  6. include 'lib/postToGooglePlus.php';
  7. include 'cfg/secret.php';
  9. function ReadTweet($tweet) {
  10.     # Find the text of the tweet; decode HTML entities
  11.     $tweet_text = html_entity_decode($tweet["text"], ENT_NOQUOTES, 'UTF-8');
  13.     # Attachment to be used for Google+ and Facebook
  14.    # Either a picture or a web link – if any
  15.     $tweet_attach = "";
  17.     # Find media in tweet; loop through the media array
  18.     $tw_media = array();
  19.     if (isset($tweet["entities"]["media"])) {
  20.         foreach ($tweet["entities"]["media"] as $media) {
  21.             $media_url = $media["media_url"];
  23.             # Strip the path part from the attachment
  24.             $img = preg_replace("$.*/$", "", $media_url);
  26.             # Fetch the picture and put it in /tmp
  27.            system("wget -q -O /tmp/$img $media_url");
  29.             # This will be our attachment if it is the first picture found
  30.            if (!$tweet_attach) {
  31.                 $tweet_attach = "/tmp/$img";
  33.                 # Remove url from tweet
  34.                 $short_url = $media['url'];
  35.                 $tweet_text = str_replace($short_url, "", $tweet_text);
  36.             }
  37.         }
  38.     }
  40.     # Find URL's in tweet; replace shortened url by the expanded url
  41.    if (isset($tweet["entities"]["urls"])) {
  42.         foreach ($tweet["entities"]["urls"] as $tw_url) {
  43.             $short_url = $tw_url["url"];
  44.             $long_url  = $tw_url["expanded_url"];
  46.             # This will be our attachment if not already found one before
  47.             if (!$tweet_attach) {
  48.                 $tweet_attach = $long_url;
  50.                 # Remove URL from tweet
  51.                 $tweet_text = str_replace($short_url, "", $tweet_text);
  52.             } else {
  53.                 # Not an attachment, replace short url by the long url
  54.                 $tweet_text = str_replace($short_url, $long_url, $tweet_text);
  55.             }
  56.         }
  57.     }
  58.     return array($tweet_text, $tweet_attach);
  59. }
  61. function PostToGooglePlus($msg, $attach) {
  62.     global $g_email, $g_passwd;
  64.     $loginError = doConnectToGooglePlus2($g_email, $g_passwd);
  65.     if (!$loginError) {
  66.         if ($attach) {
  67.             # If we have an attachment, and it points to twimg.com, make it an image attachment
  68.             if (preg_match("/twimg.com/", $attach)) {
  69.                 $lnk = array('img'=>$attach);
  70.             } else {
  71.                 $lnk = doGetGoogleUrlInfo2($attach);
  72.             }
  73.             doPostToGooglePlus2($msg, $lnk);
  74.         } else {
  75.             doPostToGooglePlus2($msg);
  76.         }
  77.     } else {
  78.         echo $loginError;
  79.     }
  80. }
  82. # Create a Twitter object
  83. $twitterObj = new EpiTwitter($consumer_key, $consumer_secret, $access_token, $access_secret);
  85. # Get tweets
  86. $status = $twitterObj->get('/statuses/user_timeline.json', array('include_entities' => 1));
  87. $response = $status->response;
  89. $tweets_done = "cfg/tweets_done";
  90. foreach ($response as $tweet) {
  91.     # Find the tweet ID
  92.     $id = $tweet['id_str'];
  94.     # If the id is not in the $tweets_done, handle it
  95.     $in_file = 'grep $id $tweets_done';
  97.     if (!$in_file) {
  98.         # Get tweet text and possible attachment
  99.         list($tweet_text, $tweet_attach) = ReadTweet($tweet);
  101.         # Send it to Google+
  102.         PostToGooglePlus($tweet_text, $tweet_attach);
  104.         # Show the tweet and attachment
  105.         echo "$tweet_text\n";
  106.         if ($tweet_attach) echo "Attachment: $tweet_attach\n";
  107.         echo "\n";
  109.         # Add the tweet ID to the $tweets_done
  110.         file_put_contents($tweets_done, "$id\n", FILE_APPEND);
  111.     }
  112. }
  114. ?>

  6 Responses to “How to post messages to Google+ using PHP”

  1. Can the code be clubbed and made a wordpress plugin so that non-techies can also benefit?

  2. Ik kon gewoon niet anders dan even hier iets invullen: erg mooie blogpost, goed geschreven,
    lekker informeel! Hoeveel post je per maand?

  3. Unusual post for programmers… i wish to see here an example to post without any plugins or free library…

  4. Hi,

    What I wanted to, post my every new twit to my Google plus page. Is there any easy way?

    Thanks in advance.


  5. It’s about time Google upped their game and released an API that allows automatic posts

  6. What I don’t understand is that Google itself claims that there is only read-only access thru the API, but the guys at NextScripts manage to have write access.

    How come they do and we don’t? In other words: if I buy their plugin, do I need something extra (a subscription, a dinner date with Google’s CEO??) to make it work?

Leave a Reply to Jizly.com Cancel reply



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Social Widgets powered by AB-WebLog.com.