Search code examples
phpframeworkscontent-management-systempermalinks

Custom CMS, pretty permalinks like commercial CMS


I am currently whipping up a very basic CMS for a personal project of mine. It is as much for my own education as anything. One question I have is how do I achieve url's / permalinks without file extentions. I understand using get variables to pull data from the DB but how do you convert this to something like www.url.com/posttitle instead of something like www.url.com/?posttitle='blablabla.

Also on a slightly different topic can anyone point me in the direction of an EASY to use framework for developing sites that deal with memberships and member listings eg craigslist.

I currently develop within wordpress and am quite capable but am less familiar with OOPHP and custom CMS development from a base level.

Thanks in advance for any help or suggestions.


Solution

  • You'd use a .htaccess file to pass all requests to your front controller (which is usually just an index.php script) and then that script matches the incoming request to a record in your database.

    For example, if you had a database table called pages with four columns: id, title, slug and content, the following would be a simple implementation…

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)$ index.php/$1 [NC,L]
    

    This tells Apache to take all requests that aren't a file or a direction and send them to index.php.

    Your index.php could then look as follows:

    <?php
    // Take request URI
    // Would be something like 'your-slug'
    $request = trim($_SERVER['REQUEST_URI'], '/');
    
    // Set up database connection and attempt to match slug
    $sql = "SELECT * FROM pages WHERE slug = ? LIMIT 1";
    $smt = $db->prepare($sql);
    $smt->execute(array($request));
    
    $page = $smt->fetchObject();
    
    if (! $page) {
        // Page was not found matching slug
        header('HTTP/1.1 404 Not Found');
        exit;
    }
    
    // Display matching page in a template
    

    From here, you can then build upon it.