Mason Peace
Mason Peace

Reputation: 93

Best way to remove = and ? from get method in PHP?

What's the best way to remove the = and ? in a URL from the get method in PHP? I'm working on the pagination structure of my website and currently this is what the URLs look like:

www.example/test/?page=3

I want it to look like this:

www.example/test/3

Can this be addressed directly in the PHP get method with some extra code or does it have to be done through an htaccess file?

This is what my htaccess file looks like right now:

RewriteBase /  
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_URI} /index\.html?$ [NC]
RewriteRule ^(.*)index\.html?$ "/$1" [NC,R=301,NE,L]

Upvotes: 1

Views: 444

Answers (2)

Anwar
Anwar

Reputation: 4246

Here is my try, I compacted some already existing answer from different StackOverflow topics dealing with URL extraction and I came up with this solution :

<?php
    function http_protocol() {
        /**
         * @see https://stackoverflow.com/a/6768831/3753055
         */
        return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://';
    }

    function http_host() {
        return $_SERVER['HTTP_HOST'];
    }

    function http_uri() {
        return parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    }

    function http_refactored_query_strings() {
        $queries = explode('&', $_SERVER['QUERY_STRING']);
        $refactoredQueries = [];

        foreach( $queries as $query ) {
            $refactoredQueries[] = filter_var(explode('=', $query)[1], FILTER_SANITIZE_STRING);
        }

        $queries = implode('/', $refactoredQueries);

        return $queries ?: '';
    }

    function http_refactored_url() {
        return http_protocol() . http_host() . http_uri() . http_refactored_query_strings();
    }

    echo http_refactored_url();
?>

Tryied with some examples :

For the query string refactoring part, I used $_SERVER['QUERY_STRING] and exploded the value to & character. because the first ? is not contained in $_SERVER['QUERY_STRING']. So you come up with lot of arrays, containing strings like page=3, view=page, ... And foreach one, you split it using = delimiter and get the second element (index : 1) to append it to the solution.

Hope it helps

Upvotes: 1

J Shubham
J Shubham

Reputation: 609

You can do this by using an intermediate page, say index.php and apply .htaccess rewrite only for index and load page based on GET[] on index.php.

You can refer this: URL rewriting in PHP without htaccess

Upvotes: 0

Related Questions