{"id":177,"date":"2010-12-09T12:52:25","date_gmt":"2010-12-09T12:52:25","guid":{"rendered":"http:\/\/www.osd.net\/blog\/?p=177"},"modified":"2010-12-28T07:24:30","modified_gmt":"2010-12-28T07:24:30","slug":"post-to-facebook-wall-using-php","status":"publish","type":"post","link":"https:\/\/www.osd.net\/blog\/web-development\/php\/post-to-facebook-wall-using-php\/","title":{"rendered":"Post to facebook wall using php"},"content":{"rendered":"<p>Getting the needed permissions and writing on an user&#8217;s facebook wall seems something complicated, but once you get some basic things you will be able to develop applications that send updates to facebook accounts.<\/p>\n<p>In order to be able to do this the account owner must give you access. If you think that by knowing the username and password you can do this you are wrong. You need to create a facebook application that the user agrees to use.<\/p>\n<h1>Create facebook application<\/h1>\n<p>First thing: create the facebook application. Go to <a title=\"create facebook application\" href=\"http:\/\/www.facebook.com\/developers\/createapp.php\" target=\"_blank\">http:\/\/www.facebook.com\/developers\/createapp.php<\/a><\/p>\n<p>If this is the first time you are here you will need to allow the built in facebook app called &#8220;Developer&#8221; to access your account.<\/p>\n<p>After completing the first basic steps (choosing a name for your application, entering captcha) you will get to the edit application details page.<\/p>\n<p>Most of the fields will be very easy to fill in. You will need to be sure you enter the application site url and domain in the &#8220;web site&#8221; tab (this is just a page that shows details about your app) and the most important one: the <strong>canvas url<\/strong>. This address will need to point to the script that will save the details you need. So let&#8217;s say it will be something like <strong>http:\/\/localhost\/fbapp\/fb_users.php?<\/strong> (don&#8217;t forget the question mark).<\/p>\n<p style=\"text-align: center;\">\n<div id=\"attachment_182\" style=\"width: 671px\" class=\"wp-caption aligncenter\"><img aria-describedby=\"caption-attachment-182\" loading=\"lazy\" class=\"size-full wp-image-182 \" title=\"Facebook Enter Canvas URL\" src=\"https:\/\/www.osd.net\/blog\/wp-content\/uploads\/2010\/12\/fb_sample1.png\" alt=\"Facebook Enter Canvas URL\" width=\"661\" height=\"357\" srcset=\"https:\/\/www.osd.net\/blog\/wp-content\/uploads\/2010\/12\/fb_sample1.png 944w, https:\/\/www.osd.net\/blog\/wp-content\/uploads\/2010\/12\/fb_sample1-300x162.png 300w, https:\/\/www.osd.net\/blog\/wp-content\/uploads\/2010\/12\/fb_sample1-150x81.png 150w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><p id=\"caption-attachment-182\" class=\"wp-caption-text\">Facebook Enter Canvas URL<\/p><\/div>\n<p>After you save the application details you should see on the summary page the application id, api key and secret (some random codes like NEH3UVX38VPU). You will need them.<\/p>\n<h1>Ask for permissions<\/h1>\n<p>Now let&#8217;s get to the point.<\/p>\n<p>You will need to download the facebook php sdk, located <a href=\"https:\/\/github.com\/facebook\/php-sdk\/zipball\/v2.1.2\">here<\/a> and save it in your application directory.<\/p>\n<p>Create a config file where you will save these values and create a database connection.<\/p>\n<p>So a sample would look like this:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\ndefine('MYSQL_HOST',     'your_db_host');\r\ndefine('MYSQL_USER',     'your_db_user');\r\ndefine('MYSQL_PASSWORD', 'your_db_password');\r\ndefine('MYSQL_DB',       'your_db_name');\r\ndefine('TABLE_PREFIX',   'your_table_prefix');\r\n\r\ntry\r\n{\r\n$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD);\r\n$dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\r\n\t$dbh-&gt;setAttribute(PDO::ATTR_PERSISTENT, true);\r\n\t$dbh-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, true);\r\n\t$dbh-&gt;setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);\r\n\t$dbh-&gt;setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);\r\n}\r\ncatch (PDOException $e)\r\n{\r\n\tprint &quot;Error!: &quot; . $e-&gt;getMessage();\r\n\tdie;\r\n}\r\ndefine('FB_APIKEY', 'YOUR_FACEBOOK_APPLICATION_API_KEY');\r\ndefine('FB_SECRET', 'YOUR_FACEBOOK_APPLICATION_SECRET');\r\nrequire_once('facebook-platform\/php\/facebook.php');\r\n?&gt;<\/pre>\n<h1>Save authentication token<\/h1>\n<p>Now we will need to create a simple script (called <strong>get_fb_approval.php<\/strong>) that redirects the user to the page where he will allow your application to access your account.<\/p>\n<p>This example can be used for a multi-user application so let&#8217;s say you will ask for the facebook username in a previous step and now you will try to get the approval for that account. Just to keep this example simple we will consider that we will receive the facebook username in get (so we will test the script like this <strong>http:\/\/localhost\/fbapp\/get_fb_approval.php?user=_YOUR_FB_USERNAME_<\/strong> )<\/p>\n<p>This script will look like this:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">&lt;?php\r\nrequire_once('config.php');\r\n$facebook = new Facebook(FB_APIKEY, FB_SECRET);     \/\/ request permissions to write on the user's wall, even when he is online.\r\n$loginUrl = $facebook-&gt;get_login_url('YOUR_CANVAS_URL_HERE?user=' . @$_GET['user'], 1, 'publish_stream,offline_access');\r\n    header('Location: ' . urldecode($loginUrl));\r\n    die;\r\n?&gt;\r\n<\/pre>\n<p>Notice that on the 3rd line you have YOUR_CANVAS_URL_HERE. Replace this with the canvas url you provided when you created the facebook app (something like <strong>http:\/\/localhost\/fbapp\/fb_users.php<\/strong>).<\/p>\n<p>This way you will tell facebook to send you the data you need to this url and also the username that you sent (so you would know how to connect the users you have with the tokens you receive)<\/p>\n<p>What we need now is the script placed at the <strong>canvas url<\/strong>.<\/p>\n<p>You also need a table with this structure:<\/p>\n<pre class=\"brush: sql; title: ; notranslate\" title=\"\">CREATE TABLE IF NOT EXISTS `fb_users` (\r\n  `fb_user_id` int(10) NOT NULL auto_increment,\r\n  `fb_user_username` varchar(30) NOT NULL,\r\n  `fb_user_uid` varchar(20) NOT NULL,\r\n  `fb_user_auth_token` varchar(100) NOT NULL,\r\n  PRIMARY KEY  (`fb_user_id`)\r\n);\r\n<\/pre>\n<p>(don&#8217;t forget about your table prefix)<\/p>\n<p>This script will look like this:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">&lt;?php\r\nrequire_once('config.php');\r\nif (isset($_GET['session']) &amp;&amp; isset($_GET['user'])) \/\/ you received the data you need\r\n{\r\n \t\t\/\/ $session = json_decode($_GET['session'], true, 512, JSON_BIGINT_AS_STRING); \/\/ this will work after php 5.3\r\n \t\t\/\/ this way it will work for older php versions\r\n \t\t$session = trim($_GET['session'], '{}');\r\n \t\t$parts = explode(',', $session);\r\n \t\t$auth_token = '';\r\n \t\tforeach ($parts as $key=&gt;$value) \/\/ extract the needed values from this array\r\n\t\t{\r\n\t\t\t$tmp = explode(':', $value);\r\n\t\t\t$var_name = trim($tmp[0], '&quot;');\r\n\t\t\t$var_val = trim($tmp[1], '&quot;');\r\n\t\t\tif ('secret' == $var_name)\r\n\t\t\t{\r\n\t\t\t\t$auth_token = $var_val;\r\n\t\t\t}\r\n                        if ('uid' == $var_name)\r\n                       {\r\n                             $uid = $var_val;\r\n                       }\r\n\t\t}\r\n\t\t$user = filter_var($_GET['user'], FILTER_SANITIZE_STRING);\r\n                $auth_token = filter_var($auth_token, FILTER_SANITIZE_STRING);\r\n                $uid = filter_var($uid, FILTER_SANITIZE_STRING);\r\n\t\t$query = '\r\n\t\t\t\t\tDELETE FROM\r\n\t\t\t\t\t\t'.TABLE_PREFIX.'fb_users\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\tfb_user_username = :username\r\n\t\t'; \/\/ delete old (maybe deprecated) user info\r\n\t\t$stmt = $dbh-&gt;prepare($query);\r\n\t\ttry\r\n\t\t{\r\n\t\t\t$stmt-&gt;bindParam(':username', $user);\r\n\t\t\t$stmt-&gt;execute();\r\n\t\t}\r\n\t\tcatch(PDOException $e)\r\n\t\t{\r\n\t\t\t\/\/debug your query\r\n\t\t}\r\n        \/\/ save the new info\r\n        $query = '\r\n                    INSERT INTO\r\n                        '.TABLE_PREFIX.'fb_users\r\n                    SET\r\n                        fb_user_username = :fb_user_username,\r\n                        fb_user_uid = :fb_user_uid,\r\n                        fb_user_auth_token = :fb_user_auth_token\r\n        ';\r\n        $stmt = $dbh-&gt;prepare($query);\r\n\t\ttry\r\n\t\t{\r\n\t\t\t$stmt-&gt;bindParam(':fb_user_username', $user);\r\n\t\t\t$stmt-&gt;bindParam(':fb_user_auth_token', $uid);\r\n\t\t\t$stmt-&gt;bindParam(':fb_user_auth_token', $auth_token);\r\n\t\t\t$stmt-&gt;execute();\r\n\t\t}\r\n\t\tcatch(PDOException $e)\r\n\t\t{\r\n                      \/\/debug your query\r\n\t\t}\r\n\t}\r\n\/\/do what you want after you save the user info\r\n<\/pre>\n<p>Now you saved the most important thing you need: the <strong>authentication token<\/strong>.<\/p>\n<h1>Post new status<\/h1>\n<p>Everything is almost done. Now how will we use this things?<\/p>\n<p>We will write a function that posts a message to someone&#8217;s wall so you will be able to use it the way you want<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">function send_to_facebook($username, $message)\r\n{\r\n        \/\/ don't forget about the database connection and to be user you included the facebook sdk\r\n\tglobal $dbh;\r\n\trequire_once('facebook-platform\/php\/facebook.php' );\r\n\t$facebook = new Facebook(FB_APIKEY, FB_SECRET);\r\n\t$query = '\r\n\t\t\t\tSELECT\r\n\t\t\t\t\t*\r\n                                FROM\r\n\t\t\t\t\t'.TABLE_PREFIX.'fb_users\r\n\t\t\t\tWHERE\r\n\t\t\t\t\tfb_user_username = :fb_user_username\r\n                               ORDER BY\r\n                                        fb_user_id DESC\r\n                               LIMIT 1\r\n\t';\r\n\t$stmt = $dbh-&gt;prepare($query);\r\n\ttry\r\n\t{\r\n\t\t$stmt-&gt;bindParam(':fb_user_username', $username);\r\n\t\t$stmt-&gt;execute();\r\n\t}\r\n\tcatch(PDOException $e)\r\n\t{\r\n              \/\/debug your query here\r\n\t}\r\n\t$info = $stmt-&gt;fetch(PDO::FETCH_ASSOC);\r\n\tif (empty($info))\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t$facebook-&gt;api_client-&gt;session_key = $facebook-&gt;do_get_session($info['fb_user_auth_token']);\r\n    try\r\n    {\r\n        $facebook-&gt;api_client-&gt;users_setStatus($message, $info['fb_user_uid']);\r\n    }\r\n    catch(Exception $e)\r\n    {\r\n        return false;\r\n    }\r\n\treturn true;\r\n}\r\n<\/pre>\n<p>That&#8217;s all.<\/p>\n<p>If you need to test this a number of times you will get the approval request page only the first time. In order to see it again you must remove your application from the list of apps you approved. You can do this <a title=\"Your list of facebook applications\" href=\"http:\/\/www.facebook.com\/settings\/?tab=applications\" target=\"_blank\">here<\/a>.<\/p>\n<p>So now you know how to: <strong>ask the user for permission<\/strong> to write on his wall, save a <strong>facebook authentication token<\/strong> and most important: how to <strong>post on his wall<\/strong>.<\/p>\n<p>If you have any questions, please feel free to add a comment to this post.<\/p>\n<p>Edit:<\/p>\n<p>As harry suggested, you can find an archive with all the needed source code to post on facebook wall <a title=\"post to facebook wall - php sample code\" href=\"https:\/\/www.osd.net\/blog\/wp-content\/uploads\/2010\/12\/fbapp.zip\">here<\/a><\/p>\n<p>You will find a file called README.txt inside the archive that tells what you need to do so that this script would work.<\/p>\n<p>The code inside the archive is a bit different since it is a full working example, not just bits.<br \/>\nThank you for the suggestion and I hope this sample will help you.<\/p>\n<div id=\"share-and-beer-container\">\t<div id=\"buy_me_a_beer_div\" class=\"single beer\">\n\t \t\n\t\t<div class=\"buy-beer\" onclick=\"document.getElementById('buy_me_a_beer_form').submit();\">\n\t\t\t<form action=\"https:\/\/www.paypal.com\/cgi-bin\/webscr\" id=\"buy_me_a_beer_form\" method=\"post\">\n\t\t\t\t<input type=\"hidden\" name=\"cmd\" value=\"_xclick\" \/>\n\t\t\t\t<input type=\"hidden\" name=\"business\" value=\"info@directaccess.ro\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"item_name\" value=\"A Beer For Post to facebook wall using php\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"item_number\" value=\"1\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"return\" value=\"https:\/\/www.osd.net\/blog\/web-development\/php\/post-to-facebook-wall-using-php\/\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"amount\" value=\"5\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"undefined_quantity\" value=\"1\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"currency_code\" value=\"USD\" \/>  \n\t\t\t<\/form>\n\t\t\t<p class=\"buy-beer-text\">If you liked this post <br \/> you can <strong>buy me a beer<\/strong><\/p>\n\t\t<\/div>\n\t<\/div><\/div>","protected":false},"excerpt":{"rendered":"<p>Getting the needed permissions and writing on an user&#8217;s facebook wall seems something complicated, but once you get some basic things you will be able to develop applications that send updates to facebook accounts. In order to be able to do this the account owner must give you access. If you think that by knowing &hellip;<\/p>\n<div class=\"cta1\"><a href=\"https:\/\/www.osd.net\/blog\/web-development\/php\/post-to-facebook-wall-using-php\/\">Read more<\/a><\/div>\n<div class=\"like-excerpt\"><div\n        class=\"fb-like\"\n        data-href=\"https:\/\/www.osd.net\/blog\/web-development\/php\/post-to-facebook-wall-using-php\/\"\n        data-layout=\"button_count\"\n        data-action=\"like\"\n        data-show-faces=\"false\"\n        data-share=\"false\">\n        <\/div><\/div>","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[14],"tags":[39,36,41,40,35,38,37],"_links":{"self":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts\/177"}],"collection":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/comments?post=177"}],"version-history":[{"count":33,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts\/177\/revisions"}],"predecessor-version":[{"id":208,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts\/177\/revisions\/208"}],"wp:attachment":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/media?parent=177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/categories?post=177"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/tags?post=177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}