Choosing the right PDF library in PHP

Generate pdf files with PHPThere are a number of PDF libraries that can help you dynamically generate .PDF files through PHP : FPDF, TCPDF, DOMPDF, CEZPDF…

I’ve long worked with FPDF which is very light (with a core file of 49ko), easy to implement but the functions provided are limited.

TCPDF first astonished me since it is able to display pure HTML in a pdf file (tables, css,… support). It also provides transformation functions that allow you to display text vertically on a .pdf file, for example. But the TCPDF core file is much too heavy : 963 ko. I run AJAX scripts that load that library at each AJAX call, which makes the time waiting for the .pdf files to be ready much too long. So, I’ve tried to make that class lighter and got rid of all comments it contained. But I still had more than 500ko of file.

I then decided to go back to FPDF and found an extension class that allows FPDF to rotate text on a page.

This tutorial is devoted to implementing FPDF (and rotation class) in PHP framework Codeigniter 2.0.3.

First download the FPDF class. You’ll find it in the download page of http://www.fpdf.org. Along with the fpdf.php class, you’ll find tutorials and docs in the downloaded file

Simply copy the file fpdf.php to /Codeigniter_2.0.3/application/libraries/ and copy the font/ directory to /Codeigniter_2.0.3/application/third_party/fpdf/

Then go to http://www.fpdf.org/fr/script/script2.php where you’ll find two classes you’ll copy in the same libraries directory:

  • The FPDF_Rotate class as an extension of the FPDF class
  • The PDF class as an extension of the FDPF_Rotate class

Be careful when creating those two libraries in Codeigniter to follow Codeigniter’s tips on creating libraries. You’ll find the files attached to the bottom of this tutorial.

You’ll also have to define the path to the FPDF font directory in /Codeigniter_2.0.3/application/config/config.php :

//FPDF FONT DIRECTORY
$config['fonts_path'] = APPPATH.'third_party/fpdf/fonts/';

Then, in your controller, simply call the library and set the necessary items :
define('FPDF_FONTPATH',$this->config->item('fonts_path'));
$this->load->library(array('fpdf','fpdf_rotate','pdf'));
$this->pdf->Open();
$this->pdf->SetFont('Arial', '', 12);
$this->pdf->SetDrawColor(0);
$this->pdf->RotatedText(10,40,'Hello World!',90);
$this->pdf->MultiCell(100,5,"Test\nSecond line");
$this->pdf->Output('./pdfs/test.pdf', 'F');

You can download the necessary files : fpdf class files

Webliography :

FPDF Class

TCPDF

DOMPDF

Codeigniter form with Ajax

codeigniterCodeIgniter (CI), the PHP framework, has evolved towards version 2.0. The main version feature is scripts are being rewritten in PHP5 (helpers in former verisons were still in PHP4). This framework is lightweight and helps developers work faster. This post will tackle :

  • the framework configuration
  • the building of a login form with an Ajax request

1. CI installation

First download CodeIgniter 2.0 source from http://codeigniter.com/ (follow the link ‘Get Source’). Unzip that file and place it in your local /www/ directory. Loading the page http://localhost:8888/codeigniter/ will display the following page (I’ve installed it on my local machine and the default port for MAMP (Mac Apache-Mysql-PHP solution) is 8888. If you’re working under windows with a WAMP solution, http://localhost/codeigniter/ will do the trick) :

Open CodeIgniter in your browser

The page which is displayed is /application/views/welcome_message.php which is loaded via /application/controllers/welcome.php. This controller contains the class Welcome which is defined as the default controller in /application/config/routes.php. If you want to reach that controller in the URL, you’ll have to use http://localhost:8888/codeigniter/index.php/welcome. In that URL, index.php is the CI front controller which is to be found in the root directory /codeigniter/. You will have to keep that index.php file but you can take it away from the URL :

  • open /config/config.php and change the index_page to $config['index_page'] = “”;
  • then add a .htaccess file to the root of your project /codeigniter/ :

SetEnv MAGIC_QUOTES 0
SetEnv PHP_VER 5
Options +FollowSymlinks -MultiViews
RewriteEngine On
DirectoryIndex index.php
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule (.*) index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule (.*) index.php?/$1 [L]

In doing so, you’ll activate Apache Mod_rewrite and be able to load http://localhost:8888/codeigniter/index.php/welcome via http://localhost:8888/codeigniter/welcome.

Now, we’ll open some CodeIgniter configuration files to setup database connection and other stuff :

1.1. Codeigniter file structure : the MVC framework

If you take a look at the /www/codeigniter/ directory, you’ll see the following structure :

Codeigniter file structure

As you can see, Codeigniter is an MVC framework. The /application/ directory is the directory of your project files :

  • the /controllers/ directory contains controller files (receive input and make requests to the models)
  • the /models/ directory contains model files (requests to the database)
  • the /views/ directory contains view files (Html, formulaires,…)

Another important directory is /system/ : it contains all the Codeigniter core files (libraries, helpers,…)

Codeigniter config files are stored in the /config/ directory. Let’s open /config/config.php and change the following lines :

  • Base site url : $config['base_url'] = “http://localhost:8888/codeigniter/”;
  • Index file : $config['index_page'] = “”;

Then open /config/database.php to set up the database connection information :

  • $db['default']['hostname'] = ‘localhost’;
  • $db['default']['username'] = ‘root’;
  • $db['default']['password'] = ‘root’;
  • $db['default']['database'] = ‘codeigniter’;

and change the values to suit your own configuration.

We also need to autoload CI core libraries and helpers that will automatically load at each request and make our work much easier. Open /config/autoload.php and change the following lines :

  • $autoload['libraries'] = array(‘database’); //to automatically load CI’s database library (class for database connection)
  • $autoload['helper'] = array(‘url’,'form’); //to automatically load CI’s url and form helpers (classes for url handling and form building)

1.2. Setting up the database

Now, turn to your browser and load PhpMyAdmin : http://localhost:8888/phpmyadmin/ and execute the following queries :
CREATE DATABASE codeigniter;
CREATE TABLE users ( user_ID int unsigned not null auto_increment primary key, username varchar(20), password varchar(32) );

2. Creating the login form

The Html form we will create is rather easy. Codeigniter is made of core libraries and helpers that you’ll find in the /system/ directory. We’ve autoloaded the form helper to help us build our form.

So, create the file in /application/views/v_login.php (I use the ‘v_’ prefix to make the difference between views (‘v_’), models (‘m_’) and controller (‘c_’) files) :
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Login</title>
<meta name="robots" content="index,follow" />
<meta name="description" content="Login" />
<meta http-equiv="Content-type" content="text/html; charset=iso8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<style type="text/css">
p { margin: 0; padding: 0; }
input.textbox { width: 120px;color: #777;height: 18px;padding: 2px;border: 1px solid #E5E5E5;vertical-align: top; }
input.button { width: auto;height: 22px;padding: 2px 5px;vertical-align: top; }
</style>
</head>
<body>
<?php
echo form_open('login');
?>
<div id="message">
</div>
<p>
<label for'username'>username</label>
<?=form_input(array('name'=>'email','value'=>'','class'=>'username textbox','style'=>'width:150px;'))?><br />
</p>
<p>
<label for'password'>password</label>
<?=form_password(array('name'=>'password','value'=>'','class'=>'password textbox'))?><br />
</p>
<p>
<?='<br />'.form_submit('submit','Login','id="submit"')?>
</p>
<?=form_close("\n")?>
</body>
</html>

As you can see, the form helper is here at work with methods like ‘form_open()’, ‘form_close()’ that will automatically generate <form> and </form> tags.

The <head> of this view already contains the link to the Jquery.js file we will need to have our Ajax script work properly : <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

The “Message” div will be used to display the Ajax Response.

The Html form is now ready but we still need to build the controller class that will load that view.

3. Creating the login controller

Create the file /application/controllers/c_login.php.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
function index() {
$this->load->view('v_login');
}
}
/* End of file c_login.php */
/* Location: ./application/controllers/c_login.php */

The constructor of this controller loads the form_validation library which we will use to check the content of the posted fields. We’ll also use the url helper to build the url of the form action attribute.

In order to load this controller in a browser, you’ll simply have to call http://localhost:8888/codeigniter/c_login

The default method that will be called is the index() method that simply loads the form view (v_login.php)

To make this controller your default controller and be able to reach it via http://localhost:8888/codeigniter/, you’ll have to change /application/config/routes.php and set the default controller to c_login:

$route['default_controller'] = “c_login”;

If you want that controller to be reached via http://localhost:8888/codeigniter/login, simply edit /application/config/routes.php and add :

$route['login'] = ‘c_login’;

4. Creating the Ajax request

Let’s go back to our /views/v_login.php.

We’ll write a short javascript that will :

  • bypass the form submit to the login controller via http
  • get the values of the necessary fields in javascript
  • pass these values to the controller via an Ajax request

Just add the following code just before the </head> tag :

<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('.username').val(),
password : $('.password').val(),
ajax : '1'
};
$.ajax({
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>

Jquery allows us to execute a function once the DOM document has been loaded : $(document).ready

The script will be triggered once the submit button is hit : $(‘#submit’).click : the # sign identifies the “id” attribute of an element of the page (the submit button in this case).

Then we store the posted variables (username and password) in the form_data array. This array also contains the “ajax” key with value “1″. This value will be checked in the controller.

Then comes the $.ajax request which contains an array :

  • url : the url the request must be sent to
  • type : variables are posted to the controller
  • data : the array of variables passed to the controller
  • success : what the script must do if the request is successful : the controller will return a piece of text that will be displayed in the $(‘#message’) div.

return : false; is used to prevent the script from actually reaching the form action url through http when the submit button is clicked.

In this example, the url “login/ajax_check” will only be reachable if you add the following to the /config/routes.php :

$route['login/ajax_check'] = 'c_login/ajax_check';

5. Creating the ajax_check controller method

We will then create a second controller method called ajax_check() to check the variables posted through Ajax.

function ajax_check() {
if($this->input->post('ajax') == '1') {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
echo 'login successful';
}
}
}

The script checks if the ajax variable posted equals to “1″. If so, we use the Codeigniter form_validation library to check the required fields and echo the validation errors if necessary.

6. Playing the script

Open Firefox and install Firebug addon if not yet installed : https://addons.mozilla.org/fr/firefox/addon/firebug/

This addon will let you check the different steps of the ajax request. Launch Firebug via Menu Tools / Firebug. Then activate the console to be able to check what’s happening in your page :

Firebug - console

Open the login page : http://localhost:8888/codeigniter/login and click “submit”. You’ll see the following Ajax response :

Ajax response

7. Checking the database : using models

We’ll change c_login controller method ajax_check and load a model to check if the user exists in the database :
function ajax_check() {
if($this->input->post('ajax') == '1') {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user == '1') {
echo 'login successful';
} else {
echo 'unknown user';
}
}
}
}

We’ve loaded a model called m_access, then we call the method check_user and send it the username and password variables.

You’ll then create the model itself in /application/models/m_access.php :
<?
class M_access extends CI_Model {
public function check_user($username,$password) {
$this->query = $this->db->select('COUNT(*)')->from('users')->where(array('username'=>$username,'password'=>$password))->limit(1)->get();
return $this->query->row_array();
}
}

You can download the necessary files : codeigniter

Code Igniter, a PHP Framework

Choosing a PHP Framework to develop websites can save you time and efforts. I’m not writing this post to write an exhaustive list of the pros and cons of different PHP frameworks but just want to highlight why I think PHP frameworks are worth trying.

In my very case, it has also led me to better programming practises.

Code Igniter - PHP FrameworkKohana - PHP5 FrameworkZend Framework

The framework I’ve developed entire projects with is Code Igniter (v.1.7.2). I have also had a go with Kohana3 (just for fun) because I was looking for a strict PHP5 lightweight framework. I have not got very deep into Zend Framework because it looks a bit heavyweight for my purposes. However, it is developed by Zend Technologies Ltd., the reference in terms of web-based PHP applications.

If you have never tried a PHP framework and are ready to view how it works in a few minutes, just try one of the official video tutorials on http://codeigniter.com/tutorials/ : strictly astonishing!

At first, I was a bit reluctant to choose a framework and preferred coding my own scripts because I tought starting to use a framework would force me into a practise I could later regret (use of coding rules imposed by the framework itself, efficiency in the long term…). This was my first thought before ever trying one.

After my first Code Igniter experience, I have changed my mind and now think they make my life easier. And even if the framework I have chosen was no longer maintained, I could easily choose another framework to develop my new websites without changing so much my programming practise.

In my opinion, the following features make a good and efficient framework :

  • a PHP 5 framework
  • an MVC (Model-View-Controller) architectural pattern
  • a set of helpers (scripts that save you time for managing urls, or form elements, for example)
  • the possibility to script your own controllers, libraries, helpers
  • a well-documented practise
  • a lightweight (thus fast loading) system

It’s all a question of powers…

PHP5-powered

The power of PHP5 frameworks like Kohana is they’re strictly OOP (Object Oriented Programming), a proof of better programming practises. Code Igniter is partly written in PHP5, helpers including PHP4 functions.

MVC-powered

The power of an MVC architectural pattern is that it allows you to structure your code : your PHP scripts are not mixed anymore with Html and MySql requests as they would be in a home-made script without a framework. In a Model-View Controller pattern,you may define specific folders to hold your controller classes, your models classes and your views. Practically speaking, a web page will call a controller. This controller may define variables or call a model to retrieve data from a database, for example. So, the model will execute the MySql query, get the data from the database and return the result to the Controller. The controller will then pass the results to the view which is like an Html template.

MY_Controller.php : writing your own controllers

A PHP Framework lets you write your own controllers. In Code Igniter, the main controller is in /system/libraries/Controller.php. Code Igniter lets you write your own controller. You should name it /system/application/libraries/MY_Controller.php. This file contains a MY_Controller class that actually extends the main Controller class :

<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
class MY_Controller extends Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array(‘my_html’,'my_url’,'my_date’));
}
}
?>

My personal controller here loads the Main Controller constructor and then loads some helpers. These helpers are not the default CI helpers that can be found in /system/helpers/ but my own rewritten helpers : my_html_helper.php, my_url_helper.php and my_date_helper.php which are copies of the original helpers to which I have added some personal functions.

Scripting websites with Code Igniter has led me to write scripts which are very short, easy to manage and wonderfully efficient.

Webliography

Code Igniter

Code Igniter Video Tutorials

Code Igniter Tutorials

Derek Allard’s tutorials

Kohana