steampixel / simplePHPRouter

This is a simple and small single class PHP router that can handel the whole url routing for your project.
MIT License
406 stars 117 forks source link

Load Dynamic URL with variable #32

Closed Keldo closed 4 years ago

Keldo commented 4 years ago

Im creating a blog plugin to work with this router.

in .htaccess DirectoryIndex index.php

RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.)$ index.php [QSA] RewriteRule ^post/([a-z])$ index.php [QSA]

in index.php Route:add('/posts/([a-z]*)', function() { $slug = $_GET['get_slug']; require 'content/plugins/blogs/blogs.php?f=read&page_slug='.$slug.''; });

What I am trying to get is the contents of that blog post. What I am getting is a 404 Error 404 :-( The requested path "/posts/the-post-title" was not found! Any assistance would be deeply appreciated.

steampixel commented 4 years ago

Hi Keldo.

Please do not modify the .htaccess file. This is not necessary in most cases. Please use the original file in your case.

You also have to add the "-" (the score char) to your rule. [a-z] just means only lowercase chars from a to z. The "-" in your post slug is unknown and will not match the rule. Please try this (untested):

'/posts/([a-z0-9-]*)'

I have also added 0-9 in case you are using numbers in your post names. Please read and learn regexp using a tutorial like this: https://www.tutorialrepublic.com/php-tutorial/php-regular-expressions.php

I also found another issue:

$slug = $_GET['get_slug']; require 'content/plugins/blogs/blogs.php?f=read&page_slug='.$slug.'';

Why do you try to read a slug from the GET Array? Please understand the logic behind $_GET (https://www.php.net/manual/en/reserved.variables.get.php). The router already will push all the matched contents inside the regexp brackets "()" into a variable:

Route:add('/posts/([a-z0-9-]*)', function($slug) {
 require 'content/plugins/blogs/blogs.php?f=read&page_slug='.$slug.'';
});

You also don't have to chain your $slug variable to the require command. Please read about the differences between calling a page and requiring a file (https://www.php.net/manual/en/function.require.php)!

Your example should finally look like this:

Route:add('/posts/([a-z0-9-]*)', function($slug) {
 require 'content/plugins/blogs/blogs.php';
});

As you can see I will not append the $slug variable to the blog.php file. This is not necessary since the contents of the required file will be placed directly to this place where the "require" command is used. This is the same as putting the contents of blog.php directly into the function. So the $slug variable should just be available inside your blog.php without doing anything.

Thats it. Hope you got it.

steampixel commented 4 years ago

I have now added a full include/require example to the index.php Use this as boilerplate.