2

I want to replace filename from URI. I need this replaced url on webpage. Example: Page url:

https://www.domain.com/...../india-hotels/dun-hotels/abc.php

My code

 echo $uri=$_SERVER['REQUEST_URI'];

It returns

...../india-hotels/dun-hotels/abc.php

But I dont need "abc.php". I need like this

...../india-hotels/dun-hotels/

This should be done using php, because I will use it on my webpage. Please suggest me to resolve this.

2
  • 3
    your last 3 urls are the same Commented Nov 28, 2016 at 5:33
  • This can be done by .htaccess also. Commented Nov 28, 2016 at 6:38

3 Answers 3

1

You could use simple, regular explode & implode to get what you want as shown by the Snippet below. Quick-Test Here.

    <?php

        // ASSUMING THAT $_SERVER['REQUEST_URI']; RETURNS THE STRING BELOW:
        $uri    =  /*$_SERVER['REQUEST_URI'];*/ "...../india-hotels/dun-hotels/abc.php";
        $parts  = explode("/", $uri);
        array_pop($parts);
        $uri    = implode("/" , $parts) . "/";
        echo $uri;    //<== YIELDS::: ...../india-hotels/dun-hotels/

Alternatively and even preferably, You could use the basename() Function in combination with str_replace() to achieve the same goal:

    <?php

        // ASSUMING THAT $_SERVER['REQUEST_URI']; RETURNS THE STRING BELOW:
        $uri        =  /*$_SERVER['REQUEST_URI'];*/ "...../india-hotels/dun-hotels/abc.php";
        $baseName   =  basename($uri);
        $uri        = str_replace($baseName, "", $uri);
        echo $uri;   //<== YIELDS::: ...../india-hotels/dun-hotels/

In a condensed form:

    <?php

        $uri        =  /*$_SERVER['REQUEST_URI'];*/ "...../india-hotels/dun-hotels/abc.php";;
        $uri        = str_replace(basename($uri), "", $uri);
        echo $uri;   //<== YIELDS::: ...../india-hotels/dun-hotels/
0

Enable rewrite module in apache.

Write this in your .htaccess file

RewriteCond %{THE_REQUEST} /index\.php [NC]

RewriteRule ^(.*?)index\.php$ /$1 [L,R=301,NC,NE]
0

I resolved it like this

$uri_ar=array();
$uri=($_SERVER['REQUEST_URI']);

if(strpos($uri,'.php')){    
  $uri_ar=explode('/',$uri);

  array_pop($uri_ar);
  $uri=implode('/',$uri_ar);

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.