PHP Hooks System

After reading Explaining Hooks, finally I understand the concept of hooks in PHP and why people use it in WordPress and say WP codes is poetry.

The general idea is, in a web application, during the runtime of the program it go through stages of processes, such as connecting to database, start the session, rendering template etc. These are known as events. When these events occured during the runtime of the program, some external code can be run as additional processing to the core program. These external/additional process is known as plugin.

So, the hooks system expose these events for the plugins to attach to. So that when the event occur, the plugin will be run. Even though the concept seems simple, but there are problem that we need to handle:

Which plugin to call first when this event occur? The hooks system need to have priority feature to make sure plugins are called in correct order, to produce the intended result

What plugin need to load? If load all, wouldn’t it affect the site performance? This is why plugins need to be registered to the plugins system of an application. So that, the core application know what plugins to load at what time, and what function to run.

Therefore, the hooks system need to have plugin registration section, priority section, specify the list of hooks event available and know how to handle unknown events. The plugin data can be stored in database, and stored the configuration data temporarily in cache for faster access.

Cloudflare & phpBB3

Session handling in phpBB3 requires a user to use one IP address per session, therefore if your IP address changed, you will be prompt to login again.

Cloudflare is a web caching service that cache static contents of a website by acting as the nameserver that manage the website domain name. Therefore, every request to the domain name will pass through Cloudflare system first and any cached contents will be served from Cloudflare servers instead of the web hosting server.

However, when using Cloudflare service, the REMOTE_ADDR value for PHP $_SERVER will follow Cloudflare servers IP address. Therefore, you might face problem when using phpBB (or any other web app that rely on session tied to the IP address) with this service.

So, we need to edit phpBB session.php file to grab the correct variable for the users’ real IP address. Edit includes/session.php

Find:

$this->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? (string) $_SERVER['REMOTE_ADDR'] : '';

Replace with:

$this->ip = (!empty($_SERVER['HTTP_CF_CONNECTING_IP']))
          ? (string) $_SERVER['HTTP_CF_CONNECTING_IP']
          : ((!empty($_SERVER['REMOTE_ADDR'])) ? (string) $_SERVER['REMOTE_ADDR'] : '');

HTTP_CF_CONNECTING_IP is special header value passed by Cloudflare servers containing visitors’ real IP address, and in case this variable not set, we use the good ol REMOTE_ADDR