Skip to content
Advertisement

PHP When rewrite pages url then the $_get not working

I am using this URL rewriting with PHP The Folder structure for rewriting the URLs. I am done it is working fine but after rewrite the URL the $_GET['cat_id'] is not working. How to get the data now? please help. My project is here http://199.192.21.232/~admin/category/men-items

Script

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'd+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[w-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[w-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[w-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        include( INCLUDE_DIR . $action . '.php' );
        exit();
    }
}

include( INCLUDE_DIR . '404.php' );

HTaccess

RewriteEngine On
RewriteRule ^/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

Advertisement

Answer

In the code you posted there is no $_GET['cat_id'] variable, unless there is a cat_id URL parameter on the URL being requested (which you’ve not stated).

If the .htaccess file and index.php script are located at http://example.com/~admin/ (where ~admin is an Apache per-user web directory) then a request of the form http://example.com/~admin/category/men-items (as in your example) would result in the $params['category'] array index holding the value men-items (from the named captured group in the matching regex). If that is what you are referring to? But there is no “cat_id” here.


UPDATE:

I just want now i have two links now on my website 1: /~admin/category.php?cat_id=2 and 2: /~admin/category/men-items. it will create content duplicate issue in feature i want just one link like 2: /~admin/category/men-items so need to redirect 1 link to 2

To canonicalise the URL for SEO you can do something like the following at the top of your .htaccess file:

RewriteCond %{QUERY_STRING} ^cat_id=2$
RewriteRule ^category.php$ /~admin/category/men-items [R=301,L]

If the old URL category.php still exists as a physical file then you’ll need to ensure that MultiViews is disabled in order to avoid conflicts with mod_rewrite. For example, at the very top of your .htaccess file:

Options -MultiViews
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement