4
\$\begingroup\$

I have this little piece of code which determines the base URL of PHP:

$root = $_SERVER["SERVER_NAME"];
if(basename(__FILE__) !== trim($_SERVER["PHP_SELF"], "/\\")) {
 $root .= "/" . basename(__DIR__);
}

This is working for me, but are there other solutions for this "problem," or are there any cases where this would fail?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 6, 2016 at 9:10
\$\endgroup\$
1
  • \$\begingroup\$ Can you provide an example of how this works? \$\endgroup\$ Commented Sep 6, 2016 at 8:54

1 Answer 1

3
\$\begingroup\$

Your code will work for one level deep working directories such as:

  1. servername/admin/index.php
  2. servername/sample/test.php

However, go one level deeper and it will not work. If I have servername/one/two/index.php, I will get a servername/two. It is because the basename() returns the working folder of the file.

I find this code useful for common applications:

$request = explode('/', $_SERVER['SCRIPT_NAME']);
array_pop($request);
echo $_SERVER['SERVER_NAME'] . implode('/', $request);

It makes use of server's script name. Given the sample servername/one/two/index.php, it will return /one/two/index.php. We then remove the script from the directory using explode and popping the result, and then finally concatenating it to the server name.

answered Sep 14, 2017 at 13:31
\$\endgroup\$
2
  • \$\begingroup\$ Both the OP example and your example will cause a notice in a command line environment, where $_SERVER['SERVER_NAME'] is undefined. \$\endgroup\$ Commented Sep 14, 2017 at 19:12
  • \$\begingroup\$ Yes, $_SERVER is not available in CLI because no web server is present. \$\endgroup\$ Commented Sep 16, 2017 at 1:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.