Reputation: 7235
Please consider the following URLs:
http://www.mydomain.com/a/test.php
https://www.mydomain.org/a/b/test.php
http://www.mydomain.co.nr/a/b/c/test.php
https://www.mydomain.com/a/b/c/d/test.php
http://www.mydomain.co.uk/a/b/c/d/e/test.php
https://www.mydomain.co.au.nm/a/b/c/d/e/f/test.php?var1=test1&var2=test2
Now I want to declare a constant called ACTUAL_URL in test.php file so that it contains the following outputs respectively (Lets assume that these URLs represent the main directory of the website, respectively in the order mentioned above):
http://www.mydomain.com/
https://www.mydomain.org/a/
http://www.mydomain.co.nr/a/b/
https://www.mydomain.com/a/b/c/
http://www.mydomain.co.uk/a/b/c/d/
https://www.mydomain.co.au.nm/a/b/c/d/e/
Now consider a file, 1.php located in the following locations:
http://www.mydomain.com/1.php
https://www.mydomain.org/a/1.php
http://www.mydomain.co.nr/a/b/1.php
https://www.mydomain.com/a/b/c/1.php
http://www.mydomain.co.uk/a/b/c/d/1.php
https://www.mydomain.co.au.nm/a/b/c/d/e/1.php
The PHP code for 1.php would be:
//1.php
//The folder name may remain as "a" or may change.
//But for most cases, it will be "a"
require_once('a/test.php');
//Rest of the code for the page
Few things to note:
I tried the following, but failed to get a satisfactory answer:
define("ACTUAL_URL", basename($_SERVER['PHP_SELF']) );
define("ACTUAL_URL", dirname($_SERVER['PHP_SELF']) );
define("ACTUAL_URL", $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] );
The first 2 dont provide the website URL, rather they seem to provide the physical path of the folder, which is not required. I need the accessible URL. The third one gives the domain name + folders (which is good) but contains the file name of the currently executing page and any $_GET params associated with it. For example, consider the following structure of my files in a website:
https://www.mydomain.co.au.nm/a/b/c/d/e/1.php?var1=test1&var2=test2
https://www.mydomain.co.au.nm/a/b/c/d/e/f/test.php
In the above case, I want the constant ACTUAL_URL to give me:
https://www.mydomain.co.au.nm/a/b/c/d/e/
Relative path to test.php will always be included in 1.php file.
So how can I achieve the above indicated functionality?
Upvotes: 0
Views: 3859
Reputation: 162771
You can use the dirname()
function twice. Once to get rid of the filename (and any querystring variables) and another time to traverse up one directory.
dirname(dirname($_SERVER["REQUEST_URI"]));
Please note, this won't work on files in the root directory of the website. All your paths will need to be at least 1 folder deep.
Really though, this whole approach is questionable from a security standpoint. Allowing the client to pass in paths which ultimately get chopped up and passed into require_once
opens your application up to path traversal attacks. If you are going to do this, make sure to validate/sanitize the input.
Upvotes: 1