PHP Classes
PHP Classes
elePHPant
Icontem

How to Create a Simple PHP CMS Tutorial with SEO Friendly URL PHP Generated Links

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Simpl...   Post a comment Post a comment   See comments See comments (15)   Trackbacks (0)  

Author:

Updated on: 2017-07-12

Posted on:

Categories: PHP Tutorials

Nowadays search engines like Google value more and more the user experience provided by the sites to rank their site pages well. So, SEO (Search Engine Optimization) often means making the sites more user friendly.

One aspect that contributes to Web site pages being ranked well is to have friendly URLs that allow the user to know what pages are about just looking at the URLs.

Read this tutorial to learn how to create a simple content management system that uses user friendly URLs for the content pages, so you can implement in your own projects without having to use other large CMS systems.




Contents

Simple CMS PHP Tutorial

PHP SEO Friendly URL Links

All Roads Lead to Rome: Handling all Requests with One Script

Welcome to index.php

How to Get the Details of Friendly SEO URL PHP Script

Create SEO Links in the Administration Interface

Download the Complete SEO PHP Script CMS Package


Simple CMS PHP Tutorial

Search Engine Optimization (SEO) is very important for any web site today. if you do not optimize your web site no one will find you on search engines. And there is no use for a web site if no one can find it.

This tutorial explains just one aspect of SEO, which is to have pages with friendly URLs. Many years ago we were all mad about phpNuke or Joomla, but they had one nasty problem, the page links looked to ugly: "index.php?id=653&page_type=blog&lang=en". They were very hard to type and they all looked the same. Search engines like Google also do not like these types of URLs.

Then a new generation of CMS came out, some using for instance the CodeIgniter framework, others using Moodle or Drupal. But they also had their own SEO problems. You still can find them on-line today, but a new hero came out very fast after that was Wordpress.

One pitfall any of these CMSs have is that they are made for general purposes sites. For example Wordpress started as a blogging system, now offers plug ins to make any sort of Web sites. But for a system like that you need huge classes, too much code, too much plug-ins and too much maintenance.

Another thing is that you cannot sell GPL licenced code for clients without opening the source code. They will eventually hear somewhere that you made them pay for an open source software, and they may not like that.

Given this, probably the best solution is to make your own CMS, lightweight. You can licence it as ever you want, you know it very well as you wrote it and it is good to have a custom solution with a custom database structure.

The problem we will face is that we will return to the "index.php?id=653&page_type=blog&lang=en" problem. So lets see how to make a simple CMS with SEO friendly URL's.

PHP SEO Friendly URL Links

SEO friendly links must have the page title in it, they need to be readable and they must get rid of index.php. For example "how-to-make-seo-friendly-links" or "making-a-class-for-php-classes-site", as you can see has no index.php in it, there isn't any file name extension what so ever in the end, it is very readable and you can get the title from the link. One important point is that these links must be dynamically generated, as this is the idea of having a CMS.

So let us get back to "index.php?id=653&page_type=blog&lang=en", when we resolve it we have "index.php", it is the main PHP file processing for all requests in the CMS.

We have the ID of the article or the page, we have a page type, in this case "blog", but it can be anything, product, article or blog. Finally we have a language, in this case it is for sites with more than one language, in this tutorial I will skip the language. We need to mimic the same functionality in our "how-to-make-seo-friendly-links" link, but we do not have any element of these up, so this is how we do it:

  1. Redirect all URL requests to one place for processing.
  2. Check a table of links and get the data we need, ID and type.
  3. Depending on the element type we call a suitable plug-in to process and show the data.

All Roads Lead to Rome: Handling all Requests with One Script

If we want all URLs to be handled by one script, let's say index.php, we need then top configure the .htaccess file. We need to have an Apache on our hosting or some other Web server that provides equivalent control of configuration via a .htaccess file. The .htaccess file must enable the URL rewriting module using the RewriteEngine directive. Then just add a rule for all traffic to go to index.php.

RewriteEngine On
RewriteBase /cms/

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

It is important to set these directives carefully. In the example above I am redirecting all traffic to index.php except someone accesses a PHP or HTML file directly, or if the request path is in folders images, CSS or JS. That is where my images, CSS and JavaScript files usually are.

The use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI.

Welcome to index.php

Now we got all traffic be handled to index.php, here we need to do a general check: who came here and what he needs. index.php will be like a traffic manager. We need to catch the coming link and query a special table in a MySQL database with all our previously generated links, we get the ID and Type of the page associated with the link URL. Let us see the table structure first.

CREATE TABLE IF NOT EXISTS `members` (
  `memberID` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL DEFAULT '',
  `password` varchar(60) NOT NULL DEFAULT '',
  PRIMARY KEY (`memberID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

INSERT INTO `members` (`memberID`, `username`, `password`) VALUES
(1, 'admin', '$1$8I4.v32.$bV9MWNrNAFA1bdD/JS/FW1');
// Username - admin , Password - demo
-----------------------------

In this case element will reflect the ID of the page and urltype as its type. Now let us see the PHP code:

<?php
 error_reporting(E_ALL & ~E_NOTICE & ~E_USER_NOTICE);
define('pageclassconst', TRUE);
include_once 'admin/pages/pageClass.php';
$pageClass=new pagesClass();
$pageList=$pageClass->listPages();
$pid=$_GET[pid];
if($pid==""){
    $pageDetails=$pageClass->particularPageSlug($pageList[0]['URL']);
}
else
{
    $pageDetails=$pageClass->particularPageSlug($pid);
    if($pageDetails[id]==""){
        header("location:404.php");
    }
}
?>

As you can see, first we got the request URL, "$pid". Then we queried the database with a statement to get the type and ID of our element. If the element does not exist we redirect the code to a custom "page not found" page.

How to Get the Details of Friendly SEO URL PHP Script

After getting the type and ID of our element, it is easy to do the rest. We need to make another query to get the element details depending on the URL type.

So let us suppose we have two types of elements in our CMS: products and blogs. If it is a blog we query the blogs table and require the blog.php file to process the page. If it is a product we query the products table and get its details, then we call products.php to show that template. These are the products and blogs tables:

CREATE TABLE IF NOT EXISTS `pages` (
  `pageID` int(11) NOT NULL AUTO_INCREMENT,
  `pageTitle` varchar(255) DEFAULT NULL,
  `isRoot` int(11) NOT NULL DEFAULT '1',
  `pageCont` text,
  PRIMARY KEY (`pageID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
----------------------------------

CREATE TABLE IF NOT EXISTS `webpages` (
  `id` int(9) NOT NULL AUTO_INCREMENT,
  `Title` varchar(255) NOT NULL,
  `URL` varchar(255) NOT NULL,
  `Keywords` varchar(150) NOT NULL,
  `Description` varchar(250) DEFAULT NULL,
  `PageDetails` varchar(5000) DEFAULT NULL,
  `PageName` varchar(90) DEFAULT NULL,
  `PageType` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;


public function particularPageSlug($id) {
        $list="select * from webpages where URL='$id'";
        $result=  $this->query($list);
        $count=  $result->num_rows;
        if($count < 1){}else{
            while($row= $result->fetch_array(3)){
                return $row;
            }
        }
    }

Create SEO Links in the Administration Interface

We have seen how to redirect URL requests to index.php and show the requested product or blog depending on the URL. But now we need to see how in administration we create these links and fill them in "urls" table.

When adding a blog we will insert all data in the "blogs" table, so we will need to get the insert blog post ID. We will use that ID in our "urls" table. We also need the title to create the link for it. That is where we will use create_link() function.

<?php
 public function addPage($data){
        $message=new alertClass();
        $data["PageDetails"]=$this->real_escape_string($data["PageDetails"]);
        $data["URL"]=$this->slug($data["URL"]);
        if($this->dulicatePage($data["URL"])<1){
        $keys=array_keys($data);
        $values=array_values($data);
        date_default_timezone_set ("Asia/Kolkata");
        $table="webpages";
        $query='INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ("'.implode('","', $values).'")';
        $result=  $this->query($query) or die($this->error);
        if($result){
            unset($_POST);
            return $message->getAlert("Page is added ", "success");
        }
        else
        {
            return $message->getAlert("Error while adding page", "error");
        }
        }
        else
        {
            return $message->getAlert("Already Exists", "error");
        }
    }
?>

As you can see we always insert the blog first, then get it's inserted ID, and get the title. Then we create a new URL from the title using create_link function so we can insert a new row in urls table. 

And now lets see how "slug" function looks like:

<?php
 private function slug($string){
       $string = strtolower(trim($string));
    $string = str_replace("'", '', $string);
    $string = preg_replace('#[^a-z\-]+#', '-', $string);
    $string = preg_replace('#_{2,}#', '_', $string);
    $string = preg_replace('#_-_#', '-', $string);
    $string = preg_replace('#(^_+|_+$)#D', '', $string);
    return preg_replace('#(^-+|-+$)#D', '', $string);
}
public function dulicatePage($name){
        $check="select * from webpages where URL='$name'";
        $result=  $this->query($check);
        $count=  $result->num_rows;
        if($count < 1){return 0;}else{return $count;}
    }
?>

The "slug" function gets the title of the blog or the product and makes it as a lower case string. Then it removes any special characters with a series of str_replace lines and replaces any whitespaces with "-" character.

The result is a SEO friendly URL, which we will need to check if it is already used in the URLs table. We do not want any duplicates, all URLs need to be unique in that table. If the URL is found, we return the result to be inserted.

In case we already have that URL, we then use dulicatePage function to check the URL Slug duplicate. Then we call "slug" recursively until we get a unique URL for insertion.

This code is written for the tutorial in a simple way so you can understand the concept. It is not to be taken as something well tested in a real CMS.

For more details you can check the detailed example at here.

Download the Complete SEO PHP Script CMS Package

Creating user and SEO friendly URLs is not hard. Many existing CMS take care of that for you. But if for some reason you need to implement your own solution with needing a full blown CMS, this article presented the basic steps that you can follow to solve this matter without depending on other software.

You can download and install the the complete package described in this article here as a ZIP archive or install it using the PHP Composer tool.

If you liked this article or you have any questions, just post a comment to the article here.




You need to be a registered user or login to post a comment

Login Immediately with your account on:

FacebookGmail
HotmailStackOverflow
GitHubYahoo


Comments:

4. Thanks For The Pointer - Lee Davis (2015-08-31 19:06)
Well done for advocating modern code usage... - 4 replies
Read the whole comment and replies

2. Or Use Laravel - Kayla Anderson (2015-08-06 20:45)
Or Use Laravel... - 4 replies
Read the whole comment and replies

1. Further... - Till Wehowski (2015-08-06 19:29)
SQL OT... - 2 replies
Read the whole comment and replies

3. You can charge using GPL - Nick (2015-08-06 18:50)
You can charge using GPL... - 1 reply
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Simpl...   Post a comment Post a comment   See comments See comments (15)   Trackbacks (0)