0

If the URL is the following :

If: http://www.imvu-e.com/products/dnr/
Then: http://www.imvu-e.com/products/dnr/

If: http://www.imvu-e.com/products/dnr/?
Then: http://www.imvu-e.com/products/dnr/

If: http://www.imvu-e.com/products/dnr/index.php
Then: http://www.imvu-e.com/products/dnr/

If: http://www.imvu-e.com/products/dnr/page.php?var=2
Then: http://www.imvu-e.com/products/dnr/

If: http://www.imvu-e.com/products/dnr
Then: http://www.imvu-e.com/products/

How can I do this?

My attempt:

print "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/";
0

4 Answers 4

1

Have a look at parse_url() function.

It returns anything you need.

Simply print_r() the result from parse_url to see what you get back. You probably want something like:

$ARRurlParts = parse_url($orgurl);

$newURL = $ARRelem["scheme"].
"://".$ARRelem["host"].
((isset($ARRelem["port"]))?":".$ARRelem["port"]:"").
$ARRelem["path"];
Sign up to request clarification or add additional context in comments.

Comments

1

The issue with your "attempt" is that $_SERVER['REQUEST_URI'] will contain everything the user passed, including index.php and question mark and possibly more. In order to get what you are after, you need to parse the $_SERVER['REQUEST_URI']:

  • If it ends with a slash /, leave it as it it
  • Otherwise, find the last slash in the string and take the substring from the beginning up to and including this slash
  • Finally append the result onto the http:// (or https:// with the domain name)

Comments

1

Ended up going with this

$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
$address = $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
$parseUrl = parse_url(trim($address));
$parent = (substr($parseUrl['path'], -1) == '/') ? $parseUrl['path'] : dirname($parseUrl['path']) . "/";
return $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['port'] . $parent;

Inspired in part by Erwin Moller's answer (Why I voted it) and snipplets across web.

Comments

-1

You can strip everything from the last backslash till the end of the string. I am pretty sure that dirname($_SERVER['REQUEST_URI']) won't do the job. You can also try using dirname($_SERVER['SCRIPT_FILENAME']). The last shoud work if you don't have some fancy .htaccess rewrite rules.

2 Comments

I'm sure you meant "slash" and not "back-slash".
Yep, this is the "forward slash" or simply "slash"

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.