John Davidson

database - PHP routing system for blog posts

0 comments
Message:


I have managed to create a simple routing system however I'm a bit stuck on how to make it more dynamic. In this case I have got a blog post set up in my routing which is hard coded. If i click a dynamic link in my website that requires the /views/blog/page.php how can I get the system to work out what the page_slug is and append the page_slug so that it works without hard coding the links into it?


switch ($request) {

case '':
case '/':
require __DIR__ . '/views/index.php';
break;

case '/blog/blog-post-one':
$_GET['page_slug'] = 'blog-post-one';
require __DIR__ . '/views/blog/page.php';
break;
}

I've added my .htaccess file below just in case


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]


My Answer:
To make your routing system more dynamic and handle dynamic links, you can modify your routing logic to extract the page slug from the URL and pass it as a parameter to your page.php file. Here's an example of how you can achieve this:

php
$request = $_SERVER['REQUEST_URI'];

// Extract the page slug from the URL
$page_slug = trim(parse_url($request, PHP_URL_PATH), '/');

switch ($page_slug) {
case '':
require __DIR__ . '/views/index.php';
break;

case 'blog':
// Handle blog page
require __DIR__ . '/views/blog.php';
break;

default:
// Handle dynamic blog post pages
$_GET['page_slug'] = $page_slug;
require __DIR__ . '/views/blog/page.php';
break;
}


With this updated logic, the routing system will extract the page slug from the URL and pass it as a parameter to the page.php file. This way, you can handle dynamic blog post pages without hardcoding the links.

Additionally, you may need to update your .htaccess file to pass the request URI as a query parameter to index.php. Here's an example of how you can update your .htaccess file:


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php?url=%{REQUEST_URI} [QSA,L]


With these changes, your routing system should be able to handle dynamic blog post pages based on the page slug extracted from the URL.

Rate this post

5 of 5 based on 8100 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us