All posts in Code

PHP for Beginners – Week 13 – The Poll Post-mortem

Hi all

Last week I ran a simple poll, and I mentioned that it was a experiment of sorts. Well, the results weren’t what I wanted, that is for certain, but oh well…

Only 3 people besides my test runs that were in the DB went and did the poll.

Sad day, but its a good sign actually. That means that I have helped 3 people, more than most has helped. So I see it as a win :)

Now, for the 3 that did do the poll, please make contact with me on Twitter as I have a invite for each of you to the exciting new world of social coding over at CodeSnipp.it

For the rest, you would have to apply for a invite.

So, for this week I will leave you all with this question: Should I continue trying to help you via a PHP for beginners series? You can vote over at the poll and the code is still available on DropBox

Chris M: Guys, if you’re interested in these weekly code releases, please take the time to vote by clicking here (it’ll take you a matter of seconds).

SEO limitations with advanced WordPress Categories

I’ve been working on a really big WordPress (just using WordPress for example sake, it could be any CMS really) site for the last couple months and have run into an interesting situation where SEO cannot be used to its fullest because of the nature of dynamic categories.

Let me paint the picture – The site has a number of parent categories as well as children categories. For the sake of this discussion, let’s say 100 parent categories, each with 1000 children. In other words, there are 100000 possible “pages” that you can land on, in other words, there’s no quick cut to creating a large switch statement to include in the header ;)

Now, for each page, it would be ideal to be able to give custom meta data (title, description and keywords) aposed to using the dynamic nature of the CMS, which would just build the meta data from the $current_category or whatever. ie. $blogname | $current_category.

All in one SEO, HeadSpace, Ultimate, you name it, none of these can really go as deep as this so as to allow for the custom attachment of meta data to each category relationship.

Example:

http://www.thesite.com/category/cars/ford

What we’d want is to assign a custom title, such as:

Cape Town Cars | Ford Models (manually entered)

As you can see, this isn’t something like:

Cars | Ford OR Cars | Fords Cars (dynamically generated)

It cannot be dynamic, if it’s dynamic, it’s not really ideal if you’re very interested in SEO – you’ll follow this if you know WordPress (or any CMS really) and are very precise with SEO.

There’s space for a plugin to be developed for this I’m sure, but right now I can’t find an ideal solution.

Anyone got any clues?

PHP for Beginners – Week 12 – The Poll

For this weeks tutorial, I opted to make a poll :)

Not going into the code this week, so head on over to PHP Tutorials Poll and take the poll

If you want the code, it is available via DropBox

The reason why I am not going into the code this week is:

  • The code is very well documented and easy readable
  • And this is somewhat of a experiment :)

Welcome WordPress 3 “Thelonious”

We’ve all been waiting for the release of WordPress 3.0 and it’s finally here! By far the best release thus far and it’s really exciting exploring all the new features.

Personally, I love the new look for the dashboard, it’s far sleaker and stream-lined than before, which I enjoy and the extra functionality is awesome. Being able to choose the administrative username and password whilst installing the software is what caught my eye first, I’m tired of having to do user management the minute it’s installed every time, so this is a great change for me. From a client perspective, I love the fact that helps menus are available on every page, this is going to save a lot of time.

The new menu system and custom posts are great additions to this release, both will be used over and over again, no doubt about that. I’m not going to go on about the functionality, rather take a watch of the video:

You can click here to read the official release.

I’m really happy to hear that the team is now going to concentrate on the WordPress community for a while, rather than immediately working on other release.

PHP for Beginners – Week 11 – Final Recap on Arrays and Loops

As was mentioned in last week’s post, I am stepping back a bit, just to make certain everyone is on-par with what is required to know for the next bit to follow.

Arrays

An array is what you turn to when you find yourself creating similar variables over and over. Two words are used when referring to the contents of an array. Those words are “key” and “value”. Every array has at least 1 key and value. They will always come in pairs as the key refers to the value. There are three types of arrays: Associative, Numeric, and Multidimensional. Multidimensional arrays are simply arrays within arrays. Let’s take a brief look at the first two.

Associative Arrays

An associative array is helpful in that the key is declared by the programmer somewhere thus giving context to the value. For example I will create an array containing personal information about myself. Below you will see two ways of laying out the array in PHP. The purpose of the second is only for organization and ease of reading.

<?php
$personalInfo = array( “name” => “Christopher Mills”, “occupation” => “SEO Master”, “location” => “Cape Town, South Africa” );
?>

<?php
$personalInfo = array(
‘name’ => ‘John Clarke’,
‘occupation’ => ‘Web Developer’,
‘age’ => 26,
‘location’ => ‘Cape Town, South Africa’
);
?>

That’s great and all – but how do I get my information to display in HTML? I’m glad you asked! It’s very similar to displaying a variable but you add one little extra piece of data: the key.

<p>My name is <?php echo $personalInfo['name']; ?> and I am a <?php echo $personalInfo['occupation']; ?> in <?php echo $personalInfo['location']; ?> and am <?php echo $personalInfo['age']; ?> years old.</p>

Numeric Arrays

Sometimes you don’t need to have a word associated with a value within an array. In that case you will use a numeric array which is actually created by default in PHP. Above we used the equal sign followed by the greater than sign (=>) to set array values to keys. With numeric arrays you can simply set the values and the key is assumed incrementally. Let’s take a look:

<?php
$personalInfo = array(
‘name’ => ‘Erik Reagan’,
‘occupation’ => ‘Web Developer’,
‘age’ => 23,
‘location’ => ‘Savannah, GA USA’
);
$fruit = array( ‘apple’, ‘orange’, ‘grapes’ );
?>

As you can see we have done nothing but put values in this array. PHP took care of the keys for us. As far as you beginners are concerned keys ALWAYS start at the number 0 and increase by 1 with each new array element. As you go deeper into learning about arrays you will learn that you can manipulate them at will – but that is not covered here today. “How do I know what key to use”, you may ask. The easy way in our example is just to start at zero and find your element. For example the key for “apple” is 0, the key for “orange” is 1 and the key for “grapes” is 2. Pretty simple, huh? :) Well sometimes your arrays will get huge and go up into the 10s and possibly hundreds. No one wants to sit there and count that mess. Your first instinct may be to simply run “echo $fruit” but it will only spit out the word “Array”. PHP gives us a few simple ways to review our array data. Let’s look at two of them.

<?php
$personalInfo = array(
‘name’ => ‘Erik Reagan’,
‘occupation’ => ‘Web Developer’,
‘age’ => 23,
‘location’ => ‘Savannah, GA USA’
);
$fruit = array( ‘apple’, ‘orange’, ‘grapes’ );
print_r( $personalInfo );
var_dump( $fruit );
?>

Note that running these in your browser may produce something quite nasty looking. The first array will especially be unattractive and perhaps difficult to read. It may benefit you to throw <pre></pre> tags around those two commands so that the white space is pre-formatted correctly. Assuming you have placed these tags around the command you should have the following printed back to you:

Array
(
[0] => apple
[1] => orange
[2] => grapes
)
array(4) {
["name"]=>
string(11) “John Clarke”
["occupation"]=>
string(13) “Web Developer”
["age"]=>
int(26)
["location"]=>
string(23) “Cape Town, South Africa”
}

The first function, print_r(), will simply print the structure and contents of your array. The keys will be on the left in brackets and the values will be to the right of the corresponding keys. In the second function, var_dump(), you learn and bit more about your data. Notice the “age” key in the $personalInfo array. The value is not in quotes like the other values are. I did this so that you could distinguish between two types of data in PHP. Anything in quotes is considered a string and in the case of the “age” data it is an integer. I won’t go into details of the other types of data but I point this out because the var_dump() function gives you some useful information.

Notice the first bit which comes in the first line “array(4)“. The first bit dumped saying “This is an array and it contains 4 sets of data”. Going down to the next line you get your key you see the first key and then it says “string(11)“. This is saying “This is a string and it is 11 characters in length” (keep in mind that a blank space is considered a character). Jump down to the “age” key and notice it says int(23). This is saying “This is an integer with a value of 23″.

Now that you know how to use print_r() and var_dump() we will move on to looping through this data.

Multidimensional Arrays

 

As mentioned above a multidimensional array is simply an array that contains at least one additional array as a value. I will run with the “personalInfo” example and create an array for a staff team.

<?php
$company = array(
‘info’ => array(
‘name’ => ‘iMod’,
‘location’ => ‘Cape Town, South Africa’,
‘website’ => ‘http://www.imod.co.za’),
‘staff’ => array(
array(‘name’ => ‘Kermit the Frog’, ‘position’ => ‘CEO’ ),
array(‘name’ => ‘Hiro Nakamura’, ‘position’ => ‘Art Director’ ),
array(‘name’ => ‘Willy Wonka’, ‘position’ => ‘Web Developer’ )
)
);
?>

As you can see multidimensional arrays can get intricate. This is an odd example because typically this type of data would be stored in a database and pulled in with PHP later. However, for the sake of learning about arrays we will start with the data within PHP. The first key in this array is called ‘info’ and it’s value is actually an associative array containing company information. The second key of our $company array is ‘staff’ and it’s value is a numeric array. Let’s take a look at the structure before we begin. Running print_r($company) will produce the following:

Array
(
    [info] => Array
        (
            [name] => iMod
            [location] => Cape Town, South Africa
            [website] => http://www.imod.co.za
        )

    [staff] => Array
        (
            [0] => Array
                (
                    [name] => Kermit the Frog
                    [position] => CEO
                )

            [1] => Array
                (
                    [name] => Hiro Nakamura
                    [position] => Art Director
                )

            [2] => Array
                (
                    [name] => Willy Wonka
                    [position] => Web Developer
                )

        )

)

Now our company information is ready to be accessed. We access the internal arrays the same way we accessed our personal information earlier. Here’s an example of using data from this multidimensional array:

<h1><?php echo $company['info']['name']; ?></h1>

<p>Located in <?php echo $company['info']['location']; ?> and online at <a href=”<?php echo $company['info']['website']; ?>”><?php echo $company['info']['website']; ?></a>.</p>

<h2>Our CEO</h2>
<p><?php echo $company['staff'][0]['name']; ?></p>

Now that we have a grasp on arrays lets jump into loops which will minimize the time we spend parsing the array data.

Loops

Loops will come in quite handy as the amount of data you work with increases. We’ve gone into arrays so that naturally leads us to loops. In the last code snippet we listed a staff member within the $company array. What if we want to cycle, or loop, through each staff member and display the information in a uniform fashion? Well in comes the foreach loop. Just like the function sounds it will do a specific action for each of the elements within an array or object. It typically looks like this:

<?php
foreach( $array as $key => $value)
{
// some code here
}
?>

Notice the three variables passed to this function. The first is simply the array we are working with. The second and third variables are defined by YOU and can say anything you want. These are what refer to the array’s data inside the curly brackets. We will look at this in a moment. But first, just like the echo command has a shorthand or alternate syntax, foreach has something that will help transverse between PHP and HTML. This way it keeps the code as clean as possible. It looks like this:

<?php foreach($array as $key => $value) : ?>
<p>Some html and some php will go here</p>

<?php endforeach; ?>

You will see this format in if statements and while loops as well (in WordPress for example). Now that we’ve looked at the format of this function let’s put it in action. Going back to the company information array let’s build a nice page with that data

<?php
$company = array(
‘info’ => array(
‘name’ => ‘iMod’,
‘location’ => ‘Cape Town, South Africa’,
‘website’ => ‘http://www.imod.co.za’),
‘staff’ => array(
array(‘name’ => ‘Kermit the Frog’,'position’ => ‘CEO’),
array(‘name’ => ‘Hiro Nakamura’,'position’ => ‘Art Director’),
array(‘name’ => ‘Willy Wonka’,'position’ => ‘Web Developer’)
)
);
?>

<h1><?php echo $company['info']['name']; ?></h1>
<p>Located in <?php echo $company['info']['location']; ?> and online at <a href=”<?php echo $company['info']['website']; ?>”><?php echo $company['info']['website']; ?></a>.</p>

<h2>Our Staff</h2>

<ul>
<?php foreach( $company['staff'] as $person ) : ?>
<li><?php echo $person['name']; ?> is our <?php echo $person['position']; ?></li>
<?php endforeach; ?>
</ul>
</p>

In this instance the foreach loop cycles through each staff member and displays the HTML and PHP we told it do. I knows exactly how many staff members are in the array so it stops once it gets to the end. I’m sure you can see how useful this can become.

Conclusion

Although this tutorial may seem to ‘unleash the power of arrays and loops’ it really just scratches the surface. I highly encourage anyone interested (and that means YOU if you’re still reading this) to read through the PHP online docs for the version you are using. You can find them at php.net. We only used one type of loop in this tutorial, the foreach loop. The others have been covered in a previous post here.

5 cases where Joomla is better than WordPress

This is a question that I’ve been asked a million times and 9 out of 10 times I’m able to convince the person that WordPress definitely is better. However, there are circumstances where Joomla is a better option, let’s have a look:

  1. Sites with a huge number of articles
  2. Sites that have a large number of authors
  3. When flexible menus are required
  4. Good built-in protection
  5. Built-in messaging system

These 5 reasons where outlined by Elmalak, a freelance graphic and web designer who works with WordPress frequently.

I’m not sure if I agree with him on all the points above, I think WordPress is capable of almost all of these with the use of some custom code or the correct plugin.

What do you think about these 5 examples?

HTML5 Infographic

You knew it was coming..

html5-infographic

Click to enlarge!

Week 10 – A more detailed look at Arrays

In the past couple of weeks, I have covered more advanced topics for PHP developers. This week, however, I am stepping back a bit (as well as next week), in order to explain arrays a bit more in depth.

As I described in my last post on arrays, and array can be described as a “collection of baskets containing similiar and/or data objects”. Now these “data objects” could be anything. It could be strings, integers, or even other arrays.

So, lets do a quick example to demonstrate all of this :)

If you want to see this in action, go here

Now, say you wanted to start pushing data into the array, that didn’t relate to each other at all:

Live example is available here

From the above example you can still see that things are pretty easy, but I am starting to store values from returned functions in there as well.

Now let’s step it up a notch :) How about storing Objects in the array as well, and make it autogenerate:

A live example is visible here. Basically, as you can see from the example, you are able to store anything you want to in your array, so play with it, it really is the best way to learn it all :)

PHP for Beginners – Week 9 – Graph API and OAuth2 Integration for Facebook

This week I will building further on the Social Media platform via a Integrator into FaceBook

So, in this post I will show you the following:

  • How to check if the user session is valid, if the user successfully logged in
  • How to call the FaceBook Graph API
  • How to call the Legacy FaceBook API
  • How to update your FaceBook status dynamically via the Graph API
  • How to use FQL Query

So take a look at the demo page before we start, so that you have a idea of what will be produced :)

Alright then, down to business :)

Step 1: First download the PHP SDK Library. Now copy the facebook.php file from the /src/ directory to your project directory

Step 2: Create a file named fbmain.php. And copy below code to this file.

http://pastebin.co.za/65295

First, update $fbconfig array with your Application’s ID, API Key and Secret Key (these can be obtained here). In the code you will see that I included facebook.php via the include_once directive. If you don’t have the PHP cURL and JSON extensions installed, this line will generate a error and thus the need for the exception handling. Until these extensions are installed, this SDK will not work.

Step 3: Now create the main page (normally index.php) and put the following code in it:

http://pastebin.co.za/65298

The above code is very easy to understand. First part contains the PHP logic, then the Javascript/HTML part to show the results.

Remember: Please change the $config['baseurl'] URL to that of which you will be using. This also needs to match the URL that you specify in the application sign up process.

In the index.php file I used Javascript to generate the login/logout buttons for me. You could however have done this via the PHP method:

http://pastebin.co.za/65303

And that is that :) The version that I have on the Demo Site is a bit cleaner [obviously ;)] and you can get this version via ZIP / TAR / TAR.GZ

So, if you want more details, or have questions, post them below :)

PHP for Beginners – Week 8 – Twitter status updater via PHP and jQuery

As was promised [or mentioned ;)] in the last post, this week we are doing a jQuery and PHP enabled Twitter updater.

So, what will this all entail? Well, basically you would have the user screen (PHP Part), the script (jQuery part) that makes the user interaction easier. But what I am going to do, is extend it a bit so that you can view the last 5 updates live :)

In order to accomplish all of this, you would need to get to know the Twitter framework a bit better, not true? Well, if you go here you will be able to register your system as a actual system that would be used to update Twitter.

Then, go here to learn more about the different functions that you can call through the Twitter API

Take Note: I have already setup a application on the Twitter Dev site, so I suggest that you start there first before continuing with the coding part :) Once you have done this, you can test your queries via Twitter API Console

For the coding part this week, not going to be posting the code right here. Due to the amount of code [sorry about that people, but the OAuth library is quite secure, but you only need to include the files now and go mad :)], I decided to rather paste it all @ DropBox (and since it was easy to do this via built-in Nautilus support in Ubuntu XD), so head on over to here and get the code there :)

For those that can’t follow the code, here is a “short” flow description:

0) Users start out on connect.php which displays the “Sign in with Twitter” image hyperlinked
to redirect.php. The client credentials are saved in
config.php as $config["twitter"]["twitter_api_key"]
and $config["twitter"]["twitter_consumer_secret"].
You can save a static callback URL in the app settings page, in the config file or use a dynamic
callback URL later in step 2. In the example I use http://php.tuts.local/week8/twitter.callback.php.

1) When a user lands on redirect.php we build a new TwitterOAuth object using the client
credentials. If you have your own configuration method feel free to use it instead of config.php.

$connection = new TwitterOAuth($config["twitter"]["twitter_api_key"], $config["twitter"]["twitter_consumer_secret"]);// Use config.php client credentials

$connection = new TwitterOAuth(‘abc890′, ’123xyz’);

2) Using the built $connection object you will ask Twitter for temporary credentials. If you
wish to have a dynamic callback URL for each user you can pass a URL as a parameter.

$temporary_credentials = $connection->getRequestToken(); // Use applications registered callback.

$temporary_credentials = $connection->getRequestToken(‘http://example.com/callback.php?’);

3) Now that we have temporary credentials the user has to go to Twitter and authorize the app
to access and update their data. You can also pass a second parameter of FALSE to not use Sign
in with Twitter: http://apiwiki.twitter.com/Sign-in-with-Twitter

$redirect_url = $connection->getAuthorizeURL($temporary_credentials); // Use Sign in with Twitter

$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);

4) You will now have a Twitter URL that you must send the user to. You can add parameters and
they will return with the user in step 5.

https://twitter.com/oauth/authenticate?oauth_token=xyz123

https://twitter.com/oauth/authenticate?oauth_token=xyz123&info=abc // info will return with user

5) The user is now on twitter.com and may have to login. Once authenticated with Twitter they will
will either have to click on allow/deny, or will be automatically redirected back to the callback.

6) Now that the user has returned to twitter.callback.php and allowed access we need to build a new
TwitterOAuth object using the temporary credentials.

$connection = new TwitterOAuth($config["twitter"]["twitter_api_key"], $config["twitter"]["twitter_consumer_secret"], $_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']);

7) Now we ask Twitter for long lasting token credentials. These are specific to the application
and user and will act like a password set for future requests. If a dynamic callback URL was used
you will also have to pass the oauth_verifier parameter. Normally the token credentials would
get saved in your database but for this example we are just using sessions.

$token_credentials = $connection->getAccessToken(); // Used applications registered callback URL

$token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);

8) After getting the token credentials we redirect the user to twitter.updater.php.

9) With the token credentials we build a new TwitterOAuth object.

$connection = new TwitterOAuth($config["twitter"]["twitter_api_key"], $config["twitter"]["twitter_consumer_secret"], $token_credentials['oauth_token'],
$token_credentials['oauth_token_secret']);

10) And finally we can make requests authenticated as the user. You can use GET, POST, and DELETE API
methods. Directly copy the path from the API documentation and add an array of any parameter
you wish to include for the API method such as cursor or in_reply_to_status_id.

$content = $connection -> get(‘account/verify_credentials’);

$connection -> post(‘statuses/update’, array(‘status’ => ‘Text of status here’, ‘in_reply_to_status_id’ => 123456));

$content = $connection -> delete(‘statuses/destroy/12345′);

And that is that :) Now just load it up in your browser (remember that the connect.php file is the main file), and you will be able to post to Twitter using your own custom tool (just remember to make the changes in config.php to reflect those of your own application). This can be extended on quite a bit, as you can make a weblet out of it and have it on your desktop constantly and make posting to Twitter so much simpler ;)