Creating a blog from scratch with PHP - Part 2 SEO URLS

David Carr

Demos Tutorials Blog PHP & MySQL

Blog Series


This tutorial is extending the Creating a blog from scratch with PHP with that in mind I will only be covering new pieces of code and not the whole codebase.

This part will cover using (SEO) search engine friendly urls instead of the post id's. 

Demo

Download source files

admin demo

username: demo
password: demo

The first things to do is alter the table structure for blog_posts add another column under postTitle called postSlug datatype is varchar and length is 255

seo-structure

The postSlug will contain the post title in lower case without any spaces, they will be replaced with a - and any symbols will be removed. This will then be used as part of the url for the post.

Next create a new file in the root called .htaccess.

To use SEO urls mod rewrite is needed (this will only work on linux servers, window servers do not support mod rewrite).

To use mod rewrite it must be turned on then define the base path that any rules will use, this will be the path of the root of the server, in this case the blog is located in a folder called simpleblog-seo so that is the base path.

Next setup a rule that says if a request is made that is not a directory and not a file then pass that request to viewpost.php as a parameters to id (?id=$1)

RewriteEngine On
RewriteBase /simpleblog-seo/

RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteCond %{REQUEST_FILENAME} !-f [NC]
RewriteRule ^(.*)$ viewpost.php?id=$1 [QSA,L]

To use the id defined in the viewpost.php?id is done the same way as before by using $_GET['id'].

Next inside the includes folder create a file called functions.php and add the following function:

<?php
function slug($text){ 

  // replace non letter or digits by -
  $text = preg_replace('~[^pLd]+~u', '-', $text);

  // trim
  $text = trim($text, '-');

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // lowercase
  $text = strtolower($text);

  // remove unwanted characters
  $text = preg_replace('~[^-w]+~', '', $text);

  if (empty($text))
  {
    return 'n-a';
  }

  return $text;
}
?>

This function will be used on the add and edit post page of the admin to make the postSlug based on the postTitle.

Then open includes/config.php and include the functions file at the bottom of the file:

include('functions.php');

Next update the url inside index.php

from

<a href="'.$row['postID'].'">

to

<a href="'.$row['postSlug'].'">

Then inside viewpost.php

Change the where statement on line 5 from:

postID = :postID

to

postSlug = :postSlug

And 

$stmt->execute(array(':postID' => $_GET['id']));

to 

$stmt->execute(array(':postSlug' => $_GET['id']));

That takes care of the blog linking using the new SEO urls the add and edit page will also need to be updated to use the new postSlug field.

Open admin/add-post and replace the try block with the following:

try {

    $postSlug = slug($postTitle);

    //insert into database
    $stmt = $db->prepare('INSERT INTO blog_posts (postTitle,postSlug,postDesc,postCont,postDate) VALUES (:postTitle, :postSlug, :postDesc, :postCont, :postDate)') ;
    $stmt->execute(array(
        ':postTitle' => $postTitle,
        ':postSlug' => $postSlug,
        ':postDesc' => $postDesc,
        ':postCont' => $postCont,
        ':postDate' => date('Y-m-d H:i:s')
    ));

    //redirect to index page
    header('Location: index.php?action=added');
    exit;

}

This add postSlug to the columns and the array to be inserted the line $postSlug = slug($postTitle); calls a slug function located inside functions.php and converted the title to an seo title which will be saved to the database.

Next open admin/edit-post.php and replace the try block with:

try {

    $postSlug = slug($postTitle);

    //insert into database
    $stmt = $db->prepare('UPDATE blog_posts SET postTitle = :postTitle, postSlug = :postSlug, postDesc = :postDesc, postCont = :postCont WHERE postID = :postID') ;
    $stmt->execute(array(
        ':postTitle' => $postTitle,
        ':postSlug' => $postSlug,
        ':postDesc' => $postDesc,
        ':postCont' => $postCont,
        ':postID' => $postID
    ));

    //redirect to index page
    header('Location: index.php?action=updated');
    exit;

}

That's it now the blog can use SEO urls, you will need to edit each post so the admin creates a slug for each post.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.