Jump to content

Dynamic PHP router


Recommended Posts

Hi all, I have built a basic router for my slug urls to work. However I'm trying to make it so that if a page is created (maybe for a blog) that the router would automatically work without have to hard code it in.

This is my current code where I've hard coded the link 'post-one' to work:

    
$request = $_SERVER['REQUEST_URI'];
switch ($request) {

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

The below code won't work but hopefully gives an idea what I am trying to acheive where if a new post is created the 'page_slug' is retrieved and the dynamic link is created. Anyone know how something like this could work?

 

$request = $_SERVER['REQUEST_URI'];
switch ($request) {

	case '/blog/'.$_GET['page_slug'].'':
         $_GET['page_slug'] = $rows["page_slug"];
        require __DIR__ . '/views/blog/page.php';
        break;

Any help most appriciated.

Link to comment
Share on other sites

Simple: don't do the routing in your PHP code. Set up your web server to automatically rewrite /blog/* to /views/blog/page.php?page_slug=*.

The term you'll want to research is "URL rewriting"...

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.