0

I want to remove .php anywhere it finds it from the visible url but still use the routing functions i wrote.

Goal: shop/index.php/product/test -> shop/index/product/test or even better shop/product/test but also shop/contact.php -> shop/contact

.htacess atm works with php extension at the end of the url but not if i want to replace shop/index.php/product/test to shop/index/product/test. Tried many .htacess settings but if i change them, to work with shop/index/product/test shop/contact doesnt work and gets a 404

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

routes.php

<?php
$url = $_SERVER['REQUEST_URI'];
$indexPHPPosition = strpos($url,'index.php');
$baseUrl = substr($url,0,$indexPHPPosition);
$route = null;
if(false !== $indexPHPPosition){
    $route = substr($url,$indexPHPPosition);
    $route = str_replace('index.php','',$route);
}

if(!$route){
    require __DIR__.'/templates/index.php';
    exit();
}
if(strpos($route,'/cart/add/') !== false){
    $routeParts = explode('/',$route);
    $productId = (int)$routeParts[3];
    header("Location: ".$baseUrl."index.php");
    exit();
}

if(strpos($route,'/product/') !== false) {
    $routeParts = explode('/', $route);

    if (count($routeParts) !== 3) {
        echo "Ungültige URL";
        exit();
    }
    $slug = $routeParts[2];
    if (0 === strlen($slug)) {
        echo "Ungülites Produkt";
        exit();
    }
    require "includes/functions.inc.php";
    require "includes/dbh.inc.php";
    $product = getProductBySlug($slug,$conn);
    if (null === $product) {
        echo "Ungülites Produkt";
        exit();
    }

    require_once __DIR__ . '/templates/watchdetail.php';

    exit();
}
  • Test if the request filename with `.php` appended to it is an existing file - if so, rewrite to that. If not, handle your "fake" URLs that do not map onto the existing file system structure, afterwards. – CBroe Jan 19 '22 at 13:55
  • 4
    It's important to remember that rewrites don't "make URLs pretty", they _read_ pretty URLs, and decide what to do with them. So rather than "removing .php", think about "making a URL without .php in point to the right thing". You might find [this reference page](https://stackoverflow.com/q/20563772/157957) helpful. – IMSoP Jan 19 '22 at 14:26
  • thx for the input. I also tought about that but my problem is im just a beginner and didnt found any info how i could change my ref from a button from index.php/product to just /product and still work with my routing or what the goto is in this area. Do i need a secound routes.php or how do i get links like shop/product/test to work with my existing routes.php – Felix Mutter Jan 19 '22 at 15:09

0 Answers0