- How to create a simple PHP CMS and generate a SEO-friendly URL
- PHP SEO Friendly URL Links
- Processing all requests in one script
- Start writing index.php
- How to Get SEO Friendly URL Information
- Creating SEO Links in the Management Interface
- Reference resources
- Create SEO Friendly URL Using PHP
- Create SEO-Friendly Slug URL Using PHP
- One thought on “ Create SEO Friendly URL Using PHP ”
- Generate SEO Friendly URL from String in PHP
- Create SEO Friendly URL in PHP
- Uses
How to create a simple PHP CMS and generate a SEO-friendly URL
Search Engine Opeimization (Search Engine Opeimization) is very important for every website. If you don’t optimize your site, search engines won’t find your site. So nobody visits the website.
This tutorial explains only one aspect of SEO, so that the page has a friendly URL. Years ago we knew phpNuke and Joomla, but they all had the same problem: their web links looked ugly: «index. php? & page_type = blog & lang = en». These links all look similar and are very difficult to enter. Search engines like Google don’t like this type of URL.
Nowadays, a new generation of CMS has come out, some of which are made using CodeIgniter framework, others using Moodle or Drupal. But these CMS still have similar SEO problems. WordPress came out soon after that.
One of the drawbacks of these CMS is that they are made for general purpose sites. For example, WordPress was originally a blogging system and now provides plug-ins to create any type of website. But for such a system, you need a lot of classes, code, plug-ins and maintenance.
Another thing is that you can’t sell GPL license code to customers without getting the source code. They will eventually hear you ask them to pay for open source software, which they may not like.
In view of this, perhaps the best solution is to make your own CMS, lightweight. You can license it as you like, and it’s very clear when you write it, and you have a custom database structure.
The problem we will face is «index.php?id=653 & page_type = blog & lang = en». So let’s see how to make a CMS SEO-friendly URL.
PHP SEO Friendly URL Links
SEO friendly links must have page titles, they need to be readable, they have to get rid of index. php. For example, «how-to-make-seo-friendly-links» or «make-a-class-for-php-classes-site», as you can see, there is no index.php, no file final name extension, it is very readable, you can get the title from the link. It is very important that these links be dynamically generated.
So let’s go back to «index.php? & page_type = blog & lang = en», when we solve it, we have «index.php», which is the most important PHP file in CMS to handle all requests.
We have the article’s «id» parameter, we have a «type» parameter, in this case its value is «blog», but it can be anything, product, article or blog. Finally, we have a «lang» parameter, which applies to websites with multiple languages. In this tutorial, I will skip the «lang» parameter. We need to mimic the same functionality in the «how-to-make-seo-friendly-links» link, so we do this:
- Redirect all URL requests to one location for processing.
- Check the link table and get the data we need, id and type.
- Depending on the element type, we call the appropriate plug-in to process and display the data.
Processing all requests in one script
If we want all URLs to be processed by a script, or by the ndex.php file, we need to configure the. htaccess file. We need to install Apache on our Web server, which provides configuration control through the. htaccess file. The. htaccess file must enable the URL rewrite module using the RewriteEngine instruction. All requests can then be transferred to index.php simply by adding rules.
RewriteEngine On RewriteBase /cms/ RewriteCond % !-d [NC] RewriteCond % !-f [NC] RewriteRule ^(.*)$ index.php?pid=$1 [QSA,L]
It is important to set these instructions carefully. In the example above, I redirected all traffic to index.php unless someone accessed a PHP or HTML file directly, or requested an image, CSS or JS with a path in a folder.
Using the [NC] flag makes RewriteRule match case-insensitive. That is to say, it does not care whether letters appear in uppercase or lowercase in matched URI s.
Start writing index.php
Now that we have all the requests processed by index.php, we need to do a general check: who’s here and what he needs. index.php is like a traffic manager. We need to capture the upcoming links and query the special tables in the MySQL database using all the links we generated earlier. We get the id and type of the page associated with the link URL. Let’s first look at the table structure:
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
Let’s look at the PHP code:
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 get the «$pid» in the request URL. Then we use statements to query the database to get the type and id of the element. If this element does not exist, we redirect the code to a custom 404 page.
How to Get SEO Friendly URL Information
After getting the type and id of our element, the rest is simple. We need to initiate another request for element details based on the URL type.
So let’s assume that there are two types of elements in our CMS: products and blogs. If it’s blogs, we query the blogs table and ask the blogs.php file to process the page. If it’s products, we query the products table and get its details, and then we call products.php to display the page. 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; >> >
Creating SEO Links in the Management Interface
We have seen how to redirect the URL request to index.php and display product and blog type information based on the URL type. Now let’s see how to create these links in the administrative interface and add them to the «urls» table.
When we add a blog, we insert all the data into the «blogs» table. Now we need to get the blog id. We need to use this id in the urls table. We also need title to create links. Now we will use the create_link() function:
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 its insert ID and get the title. Then we use the create_link function to create a new URL from the title so that we can insert a new row into the urls table.
Now let’s start writing the slug() function
#', '_', $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)else > ?>
The slug() function takes the title of a blog or product and converts it to lowercase. Then remove the special characters and replace the blank characters with «-«.
We also need to check whether the URL we get already exists in the «urls» table. We need to make all URLs unique in the table.
We use the dulicatePage() function to check whether the URL is duplicated. Then we call «slug» recursively until we get the only URL.
The sample code is written in a simple way to help you understand the concepts. It should not be seen as something fully tested in a real CMS.
Reference resources
Posted by 10cn.net in PHP at Dec 02, 2018 — 7:11 AM
Create SEO Friendly URL Using PHP
In this article, I will provide you php method script to generate SEO-friendly URL for web applications using PHP.
We will discuss how to generate SEO friendly url using PHP, Now days we are using query strings in web url to pass information between your web pages.
In this article, we will learn how to generate SEO-friendly URLs from query string values.
Query string attached parameters onto end of URL after the question mark. We have defined the function to get the Search Engine Friendly Page URL from the given string.
Create SEO-Friendly Slug URL Using PHP
Let’s create a seoUrl() method that will first remove HTML tags if any are found, Then we’ll remove special characters, trim the white space.
Finally, We will replace whitespace with hyphen and convert a string into lower characters.
/** Description: Prepare SEO Friendly URL result: SEO Frinedly URL out by replacing spaces and special characters with slash(/) */ function seoUrl() < $PageTitle="id=1 & name='parvez'"; // Remove HTML Tags if found $string=strip_tags($string); // Replace special characters with white space $string=preg_replace('/[^A-Za-z0-9-]+/', ' ', $string); // Trim White Spaces and both sides $string=trim($string); // Replace whitespaces with Hyphen (-) $string=preg_replace('/[^A-Za-z0-9-]+/','/', $string); // Conver final string to lowercase $slug=strtolower($string); echo $slug; >// result: id/1/name/parvez
One thought on “ Create SEO Friendly URL Using PHP ”
nice thanks for sharing its useful code….
Generate SEO Friendly URL from String in PHP
SEO friendly URLs are designed in a way where the URL slug is optimized for SEO. The use of the SEO-friendly URL helps to improve the search engine ranking. Also, the search engine friendly URL gives an idea about the web page content. The difference between a normal URL and SEO friendly URL is given below.
- Noraml URL: https://www.example.com/posts.php?id=123
- SEO URL: https://www.example.com/php-tutorial-for-beginners
It clearly shows that the SEO URL is more human-friendly than the normal URL. From SEO URL the user can get a clear idea of what will be on the web page they are clicking. If you want to increase your website ranking on Search Engines and make it more user-friendly, you need to switch to an SEO-friendly URL. In this tutorial, we’ll show you how to generate SEO friendly URL from string using PHP.
This example script makes it easy to convert title string to SEO-friendly URL in PHP. For better usability, we will create a custom PHP function to generate a clean and SEO friendly URL slug from string.
In this tutorial, we’ll show you how to generate SEO friendly URL from string using PHP. Our example script makes it easy to convert title string to SEO friendly URL in PHP. We’ve grouped together all the PHP code into a function named generateSeoURL() . The generateSeoURL() function automatically create clean and SEO friendly URL slug from string.
Create SEO Friendly URL in PHP
The generateSeoURL() function automatically creates SEO friendly URL slug from the string using PHP. A title string needs to be passed as input and it returns a human-friendly URL string with a hyphen ( — ) as the word separator.
- $string – Required. The string which you want to convert to the SEO friendly URL.
- $wordLimit – Optional. Restrict words limit on SEO URL, default is 0 (no limit).
function generateSeoURL($string, $wordLimit = 0) <
$separator = '-';
if($wordLimit != 0) <
$wordArr = explode(' ', $string);
$string = implode(' ', array_slice($wordArr, 0, $wordLimit));
>
$quoteSeparator = preg_quote($separator, '#');
$trans = array(
'&.+?;' => '',
'[^\w\d _-]' => '',
'\s+' => $separator,
'('.$quoteSeparator.')+'=> $separator
);
$string = strip_tags($string);
foreach ($trans as $key => $val) <
$string = preg_replace('#'.$key.'#iu', $val, $string);
>
$string = strtolower($string);
return trim(trim($string, $separator));
>
Uses
Use the generateSeoURL() function to generate SEO friendly URL from title string using PHP. Provide the article title or string in the first parameter of generateSeoURL() function. If you want to restrict words on the URL, provide the number of the words otherwise can omit it.
Without Words Limit:
$postTitle = 'Generate SEO Friendly URL from String in PHP';
$seoFriendlyURL = generateSeoURL($postTitle);
// Output will be: generate-seo-friendly-url-from-string-in-php
$postTitle = 'Generate SEO Friendly URL from String in PHP';
$seoFriendlyURL = generateSeoURL($postTitle, 4);
// Output will be: generate-seo-friendly-url
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question