Category Archives: PHP

Clean URL in PHP

Have nice and clean URL on your website is mandatory to provide a better visibility on search engines. Let’s say you want a URL like that: you will have to use URL rewriting which is not the first subject of this post but for instance you will have to generate a specific string: clean-url-in-php instead of Clean URL in PHP.

You can do that by using regulars expressions:

function cleanURL($title) {
	$title = preg_replace("/[^a-zA-Z0-9/_|+ -]/", '', $title);
	$title = strtolower(trim($title, '-'));
	$title = preg_replace("/[/_|+ -]+/", '-', $title);
	return $title;

What are we doing in this function:

  1. First of all we remove any characters which are not a letter from the alphabet, a number or a special character (/,_, etc).
  2. Next we trimmed the string and lower the characters.
  3. Finally we replace character like +,[,_ with a -.

Let’s see step by step what this function is doing this string: I’m # an example !

  1. Im an example
  2. im-an-example
  3. not even needed

CakePHP: working with Elements

One of my favorite PHP framework at the moment is CakePHP, it is not very different from others frameworks like CodeIgniter, Symphony, etc.

In this article I will present you a very handy feature of CakePHP: the Elements.
An element (like it is named) is a part of a web page which can be display into multiple pages (a sort of template if you want). Here are some elements’ examples:

  • A header: with your banner, your brand logo
  • A menu: with your categories, links
  • A footer: company name, copyright

In CakePHP, Elements are located in the app/views/elements/ directory (or if you are using a custom theme you can create specific elements and put them in the /app/views/themed/your_theme_folder/elements/ directory).

So let’s get started. We will create a basic element which will display ‘Hello World!’:

<h1>Hello World</h1>

You can save this Element: app/view/elements/helloworld.ctp
The last step is to include the element in our pages, to do so you just have to request it like that:

/*For instance I want to display Hello Word on my app/views/posts/index.ctp page:*/
echo $this->element('helloworld');

Elements using Controller with requestAction

Displaying basic information is great, but it would be much more better if we could access to our data and request something like the five latest comments or posts added. This is indeed possible through the requestAction method.

First of all, we have to add a method in our controller which will allow us to retrieve the data we want to render.

/* For instance I want to display the 5 latest posts on my index page. */
public function lastposts($limit=5)
	/* We retrieve only the required fields, and configure the query. */
	$posts = $this->Post->find('all', array('fields'=>array('', '', 'Post.created'),
							   'order'=>array('Post.created desc'),
		return $posts;
	$this->set('lastposts', $posts);

Second of all, we create our element. This step is exactly the same as what we have done before, create a page called lastposts.ctp in your app/views/elements/ directory but this time there will be more code’s lines. The first thing to do in your element is to get our data, to do that you will have to use the requestAction method, now you are ready to display your latest posts:

/* First step: get the latest posts, the URL should be like your_controller_name/method_name/params */
$posts = $this->requestAction('posts/lastposts/5');
<h3>Our latest posts</h3>
<?php foreach($posts as $post): ?>
	<li><i><?php echo $post['Post']['created']; ?></i> : <?php echo $post['Post']['name']; ?></li>
<?php endforeach; ?>

To get the job done we have to display our element in a page. We have already done that before, do it again:

echo $this->element('lastposts');

You should now be able to see the posts on the page. You also may see a little issue when you try to display the page, it takes an extra time to load it. The requestAction method is the responsible.

Enable cache for requestAction

To make things right and avoid that extra consuming resources, you can and should enable the caching functionality for your element. It is very simple and your visitors, as much as your server, will see a significant reduce during the pages’ load.

echo $this->element('lastposts', array('cache'=>'1 hour');

Add a ‘Share this on twitter’ link

In this article we will discuss about how to add a link which allow your visitors to immediately share an article from your website to their twitter account. Nowadays it is a very common feature on website and it will bring new audience. You will see that it is actually pretty simple.

First step: find a nice twitter icon. When it is about icons, I always check this website: You have plenty of choice just pick up one, for this example I choose this icon:

Ok, now we are ready to create our ‘share this on twitter’ link.
Twitter is almost making all the work for us, the only thing we have to do is to access the page and add some parameters like the URL to your article.

In this example the link I should use to share this article on twitter would be:

You just need to give the link to your article. This link has to be permanent, otherwise it will not work if any changes are made.

Here is the final code to display the image and link it with twitter:

<a href="">
     <img src="twitter_button.png" alt="share this article on twitter" />

Here is the result of our example:

Of course what you can do is display a pop-up towards Twitter so your visitors can still browse your website. Here is a snippet code to do so:

		<!-- other smart stuff here... -->
		<script type="text/javascript">
			function popup_share(url, width, height)
					day = new Date();
					id = day.getTime();
					eval("page" + id + " =, '" + id + "', 'toolbar=0,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=0,width=" + width + ", height=" + height + ", left = 363, top = 144');");
		<!-- other smart stuff here... -->
		<a href="javascript:popup_share('',800,320)" title="Share on Twitter">
			<img src="twitter_button.png" alt="share this article on twitter" />

This is the basic idea you can add other parameters to indicate a title, etc. I choose twitter for the article, but you can easily adapt it for other social network websites like Facebook, MySpace, etc it is the same pattern expect that you will have to modify the URL and its parameters (which are indeed specific to each platform).

References’ basis in PHP

The first step is to answer the following question: What are references? In PHP references are a way to access to the content of a variable by others names. We will briefly cover the three different kind of references available in PHP.

1. References as a function’s parameter

By default, PHP handle the variables you send to a function locally, what I mean is what is in the function stay in the function. By passing a reference you will make your local function variable referencing to the variable in the calling scope of your application. Here is a short example with and without references.

 * Using references
function foo(&$var){
echo($a); //Will display 6
 * Without references
function foo($var){
     return $var++;
echo($a); //will display 6

2. Return by references

Another case is to return a reference. But you have to be very careful with this one because with some tricky code you can access to the private attributes of a class and indeed modify their values.
Here is a classic use of a return reference:

class Personne {
    public $age = 22;
    public function &getAge() {
        return $this->age;
$obj = new Personne();
$myAge = &$obj->getAge(); //$myAge is a reference to $obj->age, which is 22.
$obj->age = 18;
echo $myAge; //will display 18

And now we will see that we can modify a private attribute by using a return reference:

class Personne {
    private $age = 22;
    public function &getAge() {
        return $this->age;
    public function __toString(){
        return $this->age;
$obj = new Personne();
$myAge = &$obj->getAge();
$myAge = 897; //the private attribute $age has been modified
echo($obj); //unfortunately it will display 897 

3. Assign by references

The last case and the easiest is the assignment. It is done just like that:

$a =& $b;

Which means that $a and $b reference to the same content.

In conclusion, references might seems pretty useless with these examples but it is actually wise to use some of them when you are working on a complex software architecture with a lot of objects using others objects. It is also nicer to avoid the $var=foo($var).