Archive for the ‘PHP / MySQL’ Category

Integrating WordPress into a Kohana application (or any other framework)

Friday, December 9th, 2011

I recently tried to integrate a WordPress blog into a Kohana application, and it turned out to be relatively easy. The method that follows was implemented with Kohana but the same principles can be applied to any other PHP frameworks.

When integrating WordPress, what you really need most of the time is to style the blog so that it fits within your current website. You usually also want the same header and footer as in the rest of the website.

To do so, the idea is to create some API that will allow WordPress to retrieve the header and footer from your application. Then you use the PHP function file_get_contents to import and display this content.

1. Create an API controller in Kohana

First create a new controller in Kohana that will allow getting the header and footer, and output them as HTML. In my case, I simply created an “API” controller:

class Controller_Api extends Controller {
	
	public function action_header() {
		$view = View::factory('header');
		echo $view->render();
	}	
	
	public function action_footer() {
		$view = View::factory('footer');
		echo $view->render();	
	}

}

Once this is done, you can call “http://yourdomain.com/api/header” to get the header or “http://yourdomain.com/api/footer” to get the footer.

2. Install WordPress

Just install WordPress as you would normally do, in any folder at the root of your website (let’s call it “blog” in this example).

3. Create a new WordPress theme

Go to “/blog/wp-content/themes” and copy and paste the default WordPress theme (twentyeleven for 3.x) into a new folder. Rename the folder to the name of your website.

Then go into WordPress’s admin panel and select your new theme.

4. Load your own header and footer

Now you need to modify the footer and header files of the WordPress theme so that they load your own files. Something like that should work:

header.php:

<?php
$url = "http://yourdomain.com/api/header";
echo file_get_contents($url);
?>

<div class="wrapper-box">
	<div id="blog">

footer.php

<div class="clear"></div>
	</div><!-- #blog -->
		</div><!-- #wrapper-box -->

<?php echo file_get_contents("http://yourdomain.com/api/footer"); ?>

“wrapper-box” is the box where you would normally put the main content in your website. “#blog” will be the div containing WordPress’ content.

So just by doing that you should have a working WordPress blog. The main problem however is that by replacing the header you are going to lose WordPress styling. So the next section will explain how to get it back.

5. Bring back WordPress’s styling

In Kohana, modify the header template to load a style file specific for the blog (maybe disable or enable the style depending on the current URL). Don’t directly link to the theme’s style.css but rather create a new empty file (let’s call it “blog.css”). The best way is to start with an empty file and progressively add to it.

Add back WordPress’s style to “blog.css” by copying and pasting from the original theme’s “style.css”. There are some sections of the CSS file that are safe to copy and paste completely – Menu, Content, Images, Images Border, etc. Usually it’s clear from the name that the style is not going to cause any problem. Avoid the section titled “Global” or “Header” as they may change things site-wide and thus break the header, footer or other elements.

If some CSS rules conflict with your current style, just prefix them with #blog. For example, I changed the “a” styling to the following so that it doesn’t change the links in the header and footer:

#blog a {
	color: #1982D1;
	text-decoration: none;
}

#blog a:hover {
	color: #1982D1;
	text-decoration: underline;
}

Your might want to customize the CSS further to either remove some elements or change the margins to make it matches your website.

Setting up and using the Auth module in Kohana 3.1

Saturday, April 16th, 2011

The documentation about the Auth module in Kohana 3.1 is severely lacking, and the module has changed sufficiently that existing tutorials and documentations are no longer relevant.

So below is a quick tutorial on how to setup and use the module:

1) Enable the modules

If not done already, enable the needed modules in bootstrap.php. In particular, auth, database and ORM need to be enabled:

<?php
Kohana::modules(array(
    'auth'       => MODPATH.'auth',       // Basic authentication
    // 'cache'      => MODPATH.'cache',      // Caching with multiple backends
    // 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
    'database'   => MODPATH.'database',   // Database access
    // 'image'      => MODPATH.'image',      // Image manipulation
    'orm'        => MODPATH.'orm',        // Object Relationship Mapping
    // 'unittest'   => MODPATH.'unittest',   // Unit testing
    // 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
    ));
?>

2) Setup the database

– Copy the configuration file from modules/database/config/database.php to application/config/database.php
– Open it and set username, password, etc.
– Create the database schema using the SQL file in modules/orm/auth-schema-mysql.sql

You should now have a working database with all the required tables.

3) Setup the Auth module

– Copy the Auth config file from modules\auth\config\auth.php to your config folder in application/config.
– Open this file and change the driver to “ORM” and set a hash key. It can be any random value such as those generated by WordPress.
– Your file should then look like this:

<?php defined('SYSPATH') or die('No direct access allowed.');

return array(

    'driver'       => 'ORM',
    'hash_method'  => 'sha256',
    'hash_key'     => "4b 8?((~FKnpD))>8kb!B |#-uXIO24G3rc:&MG+FR{x;r#Uq4k{Ef@F4E9^-qS!",
    'lifetime'     => 1209600,
    'session_key'  => 'auth_user',

    // Username/password combinations for the Auth File driver
    'users' => array(
        // 'admin' => 'b3154acf3a344170077d11bdb5fff31532f679a1919e716a02',
    ),

);

In order for the Auth module to work, you must also set the cookie salt variable. So add this at the end of your bootstrap.php file:

Cookie::$salt = 'somerandomstring';

4) How to register a user

Once the database and Auth are setup, it is relatively easy to add a user to the database, although there are some pitfalls (see comments below). Here is the minimum code required to add a user:

<?php
$client = ORM::factory('user');
$client->email = "my@email.com";

/* Note that the username cannot contain
   certain characters such as"." or "@".
   If it does "$client->save()" is going
   to crash, and the error message is not
   helpful */
$client->username = "laurent";

/* Auth is going to automatically hash
   the password when saving the user,
   so don't do it manually */
$client->password = "mypa55word";

$client->save();
?>

After saving the user, assign a role to him (see this post comments).

5) Example login

Once this is all done, login a user is straightforwards:

<?php
$r = Auth::instance()->login("laurent", "mypa55word");
?>

You can also check if a user is currently logged in and, if so, retrieve it from the database:

<?php
$loggedIn = Auth::instance()->logged_in();
if ($loggedIn) {
    $user = Auth::instance()->get_user();
} else {
    echo "User is not logged in";
}
?>

For more information, have a look at the Auth Module API documentation.

Create a short unique ID in PHP

Tuesday, October 21st, 2008

Mads Kristensen describes a nice way of generating shorter UUIDs in C#. The idea is to take the 16 bytes of a UUID and convert them to a readable string via a Base64 encoder. The result is a string of 22 characters instead of 32, which is particularly convenient for web services since it makes the URLs 10 characters shorter.

I’ve implemented a version of it in PHP. Just copy and paste the code below and call createBase64UUID()

function createBase64UUID() {
  $uuid com_create_guid();
  $byteString "";

  // Remove the dashes from the string
  $uuid str_replace("-"""$uuid);

  // Remove the opening and closing brackets
  $uuid substr($uuid1strlen($uuid) - 2); 

  // Read the UUID string byte by byte
  for($i 0$i strlen($uuid); $i += 2) {
    // Get two hexadecimal characters
    $s substr($uuid$i2);
    // Convert them to a byte
    $d hexdec($s);
    // Convert it to a single character
    $c chr($d);
    // Append it to the byte string
    $byteString $byteString.$c;
  } 

  // Convert the byte string to a base64 string
  $b64uuid base64_encode($byteString);
  // Replace the "/" and "+" since they are reserved characters
  $b64uuid str_replace("/""_"$b64uuid);
  $b64uuid str_replace("+""-"$b64uuid);
  // Remove the trailing "=="
  $b64uuid substr($b64uuid0strlen($b64uuid) - 2); 

  return $b64uuid;
}
Copyright © Pogopixels Ltd, 2008-2018