Home > front end >  How do you put dynamic pages after the url?
How do you put dynamic pages after the url?

Time:01-31

I am creating a website in PHP with articles, where articles can be added via a form. All data is stored in a MySQL database.

First I made a separate page of each article, eg article1.html, article2.html, ... but then I got a lot of pages.

Now I saw that on other websites the articles are behind the url, eg. https://mywebsite.com/article1

I've tried searching the internet for how they do this, but I'm not sure how to look this up as I don't know what this technique is called.

Do you know what this is called or how they do this?

I had already found things about dynamically generated page and then put the url in the sitemap, but i don't know if this is the right way?

CodePudding user response:

You can create view called article, then in URL add a param, for example my-awesome-blog/article?articleId=1. In PHP code use $_REQUEST['articleID'] to get an ID from URL. If you get ID, execute MySQL query with WHERE `id` = $_REQUEST['articleID']. At the end display getted data in view.

Done!

CodePudding user response:

You have to make the page dynamic and store the data in a db. Also for rewriting url, you need to make use of the .htaccess directives. mod_rewrite is the function you will use to rewrite the url

CodePudding user response:

I guess you are looking for a router.

    class Router
    {
        public array $routes = [];

    public function Route($action, Closure $callback): void
    {
        $action = trim($action, '/');
        $action = preg_replace('/{[^}] }/', '(.*)', $action);

        $this->routes[$action] = $callback;
    }

    public function Dispatch($action): void
    {
        $action = trim($action, '/');
        $callback = null;
        $params = [];

        foreach ($this->routes as $route => $handler) {
            if (preg_match("%^{$route}$%", $action, $matches) === 1) {
                $callback = $handler;
                unset($matches[0]);
                $params = $matches;
                break;
            }
        }

        if (!$callback || !is_callable($callback)) {
            http_response_code(404);
            exit;
        }

        echo $callback($params);
    }
}

This is a router class I made myself and it is very useful for small projects.

You add routes using another "config" router.php which will need to look like:

    $route = new Router();
    
    $route->Route('/', function() {
echo "<h1>Testing route</h1>";
    });
    $route->Route('/contact', function() {
    echo "<h1>Testing route Contact</h1>";
    });
    
    
    $action = $_SERVER['REQUEST_URI'];
    
    $route->Dispatch($action);

As .htaccess you will put:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(. )$ index.php?uri=$1 [QSA,L]
  •  Tags:  
  • Related