Category Archives: PHP

PHP related posts.

Twitter feed on your website using PHP (the easy way)

Edit: This method no longer works! Twitter has updated their API and now require authentication to fetch feeds.

So I was searching around for a while for a php script to let me grab a twitter feed and format it. I found a couple that I felt did too much work for so little.. so I decided to look into creating my own script to do it and here it is.

$twitterFeed = json_decode(file_get_contents("https://twitter.com/statuses/user_timeline/jubairsaidi.json?count=5"));
if($twitterFeed){
     foreach($twitterFeed as $t) {
          $tweetText = preg_replace('#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#','<a href="$1">$1</a>', $t->text);
          $tweetText = preg_replace('/(^|\s)@([a-z0-9_]+)/i','$1<a href="http://www.twitter.com/$2">@$2</a>', $tweetText);
          echo '<p>'.$tweetText.'</p>';
          echo '<p><em>'.date('G:i F jS',strtotime($t->created_at)).'</em></p><br/>';
     }
}else{
  echo 'this feed is not available at this time';
}

Basically what i am doing here is grabbing the contents of my twitter feed by using my user name (jubairsaidi) and saying I want the json version and limit it to only 5 posts. on the same line I am using the json_decode function which basically takes a json object and converts it into a php object. Once I have this, I loop through the data (it will return 5 objects in an indexed array) I first check to see if there are any links in the tweet text and if there are I convert the link text to a actual link, then I check if there are any mentions (which doing it this way includes replies) in the tweet and make those links to that user’s twitter account, and finally I echo out the text from the post. Keep in mind that there is a lot more data to play with.. once you bring the data over and convert it to a php object, you can work with it like anything else.

Installing Facebook PHP SDK as a Library in CodeIgniter

So I searched all over the net and couldn’t really find the answer to a simple question… how do you integrate Facebook’s PHP SDK AS IS as a Library in CodeIgniter?

There are a lot of great libraries out there that add their own functionality as well as integrate, but it’s not something I was looking to do really.. the default functionality was enough.

Anyway here’s how to do this. first go here:
http://github.com/facebook/php-sdk/

download the latest version and upload the 3 files facebook.php base_facebook.php and fb_ca_chain_bundle.crt to your application/libraries/ directory.

Now rename facebook.php to Facebook.php

Now create a file in your application/config/ folder called: facebook.php

in this file you should have the following:

< ?php  
if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
$config['appId']		= 'your_app_id'; 
$config['secret']	= 'your_app_secret'; 
$config['canvas']	= true; 

Ok now save that file and open up in that same dir (application/config/) open: autoload.php and then look for: $autoload['libraries']

Add to this array ‘facebook’ so it should look like this:

$autoload['libraries'] = array('database','session','facebook');

Do keep in mind that in this case I am also loading the database and session libraries.

Once you do this, you can simply call $this->facebook to access your Facebook Library Class.

Note: DO NOT add facebook to $autoload['config'] = array();

I made this mistake and took me some time trying to figure out why it wasn’t working properly.

Passing Multidimensional arrays between two servers

For a long time I was using JSONP to accomplish this, until I figured out a nifty function called json_encode() and of course it’s sister function json_decode().

The key here is to combine them with ob_start() function which allows you to capture raw output and dump it into a variable.

here’s how it works:

on remote server test.php file:

$array = array('hello','world','!');
$jsonString = json_encode($array);
echo $jsonString;

then what you want to do on the application server is include the remote file like this:

ob_start();
include_once('http://remoteserverdomain.com/test.php');
$string = ob_get_contents();
ob_end_clean();
$newArray = json_decode($string);

and there you have it. $newArray has the data you are looking for. now this works on any depth array, the only issue (that i have found anyway) is if your server is configured to not allow remote includes; an easy fix in php.ini though. I have found this way to be a lot easier to work with and generally more secure than using JSONP to pass the data.

Alternative way of writing an if-else statement in php.

In PHP, there are a couple ways of writing an if-else statement. One is:

if($variable == 'something'){
	$result =  'the variable equals something';
}else{
	$result =  'the variable does not equal something';
}
echo $result

Another way of writing the above if-else statement is:

if ($variable == 'something') :
	$result =  'the variable equals something';
else:
	$result =  'the variable does not equal something';
endif;
echo $result

I used the first of the above syntax for a long time (the second I never really cared for).. but couple months ago, I started paying more attention to a completely different if-else statement syntax, used particularly for assigning values to a single variable based on the met conditions in the if-else statement. Here’s the example:

	$result = $variable == 'something' ? 'the variable equals something' : 'the variable does not equal something';
	echo $result;

What I like about this alternative way of writing an if-else statement is not only less code, but cleaner code as well.

You can also nest the if-else statements like this:

    $result = $test1 ? $test2 ? 'test1 true and test2 true' : 'test1 true and test2 false' : 'test1 false';
    echo $result;

ProcessData js function + php logic file structure

Bellow is a javascript function I wrote to help process ajax actions because I was finding my self repeating a lot of the event trigger functions.

function processData(logicFile, container, action, id, form, onComplete){
	var Options = new Array;
	if(action != null) {
		actionArray = action.split('~');
		if(actionArray[0] != null){
			Options.push('action=' + escape(actionArray[0]));
		}
		if(actionArray[1] != null) {
			Options.push('sub_action=' + escape(actionArray[1]));
		}
	}
	if(id != null) {
		Options.push('id=' + escape(id));
	}
	if(form != null) {
		var keyValueArray = form.split('&');
		var i = 0
		while (i < keyValueArray.length) {
			Options.push(keyValueArray[i]);
			i++;
		}
	}
	if(onComplete == null) {
		onComplete = function(data){
			$(container).html(data.responseText);
		}
	}
	$.ajax({
		type: 'POST',
		url: logicFile,
		data: Options.join('&'),
		complete: onComplete
	});
}

Now here’s how it works.

Lets start with the variables that are passed into this function.

logicFile: (string)(required)(example: ‘/users/userslogic.php’) this is the php (can be any server side language that can interface with ajax) logic file path (I would use relative to the document root).  So an example would be say your administrative panel logic file is separate from other areas of your website, say you have different logic files for different areas of your site.  For small websites it’s not necessary to break sections up into logic files but when dealing with large and complex web apps, I like to break things up a bit for organizational and security purposes.

container: (string)(required if onComplete is null, otherwise you control the output container via the onComplete function – keep reading for details)(example: ‘.user_action_result’) this is the css element for the element container that will be populated with the processed and returned result/data from the logic file.  Though it is required that this variable is assigned, it is not required for it to be a real element.

action: (string)(required) (example: ‘manage_users~add’) this is the action trigger which can take both a parent and sub action that are defined in the logic file (which will be further explained later). You will notice in the example there are two pieces delimited by a ~.  The ~ indicates that there is a sub action to this action.  in this example’s case we are triggering the action ‘manage_users’ and the of that action the sub action of ‘add’.  so you can basically access different parts of the manage_users parent action by assigning a sub action.  Note: it is not required that the action have a sub action.  the sub action (‘~add’ in this case) is optional.

id: (string)(optional)(example: ’7′) This is an optional variable used in situations where you are trying to manipulate a specific record that is uniquely identified.

form: (string)(optional)(example: ‘username=jubairsaidi&email=bogus@bogus.com’)  when working with forms of any size, this comes in very handy.  don’t be fooled by the example, that is simple how it should look like being sent, however the way I work with this variable is by applying the .serialize() jQuery function on forms so I end up simply assigning a form to a variable (example: var serializedForm = $(‘.user_form’).serialize();) so all I have to do is in the form variable position within the proccessData function I just have the serializedForm variable sent.

onComplete: (function)(optional) (example: function(){ … } ) If you wish to do more than the default action for this function which is return the result to the specified element/container, such as take the returned data and run it through additional logic, then this is where you assign that function.  it is possible to nest the processData function as many times as necessary for any given event trigger.

Now that the jQuery javascript function is covered, lets take a look at a php logic file example that the above function would interface with (note for simplicity’s sake, I chose to exclude the file security).

switch($_POST['action']) {
	case 'manage_users':
		switch($_POST['sub_action']){
			case 'show_all':
				echo('php logic pulling list of users from database and then echoes it here');
				break;
			case 'show_user':
				echo('php logic pulling user information from database and then echoes it here');
				break;
			case 'add':
				//add the logic here and then
				if($user_added){
					echo('User Added');
				}else{
					echo('User was not added.  please try again.');
				}
				break;
			case 'edit':
				//add the logic here and then
				if($user_edited){
					echo('User Edited');
				}else{
					echo('User was not edited.  please try again.');
				}
				break;
			case 'delete':
				//add the logic here and then
				if($user_deleted){
					echo('User Deleted');
				}else{
					echo('User was not deleted.  please try again.');
				}
				break;
		}
		break;
	case 'manage_comments':
		...
		break;
}

You get the idea.

now for event trigger usage. say you have a manage_users.php file that holds the interface that you use to manage your users. at the top of this file (or bottom, or included as a js file, however you choose) you should have the following.

$(document).ready(function(){
	$('a.add_user').live('click',function(){
		var addUserForm = $('form#add_user_form').serialize();
		processData('/users/userslogic.php', '.add_user_result', 'manage_users~add', null, addUserForm, null);
	});
});

So basically when ever any link with the class ‘.add_user’ is clicked, this above block is processed.  now note that I used the .live event handler in this case.  I did this because often I have action links/buttons within ajax loaded content and .click() only works on content that was loaded into the dom on page load (which ajax is post page load).

I hope this was helpful! if more you need more detail/examples/explanation, please feel free to contact me with any questions you may have.