I've been wandering for a while trying to get out of this problem.
I have a php software in which I want to know where the script is being executed.
e.g.
I have /foo/bar/home.php . In this case I would like to know that /foo/bar is my root. But if I have an example admin page /foo/bar/admin/index.php I would like to have /foo/bar in this case too.
Or
/foo/bar/foo/index.php -> /foo/bar/foo
/foo/bar/foo/randomname/home.php -> /foo/bar/foo
How can I accomplish that ?
Thanks for help
Because /foo/bar does not really sound like a filesystem path to me, I assume that this is the first part of the URL path.
How does the application know that this prefix is applied to everything? It must be installed somewhere, and if no rewriting is applied, the filesystem path layout and url path layout match on some level. This might be used to actually generate path information by subtracting some strings, but I doubt it's usefulness.
I'd opt for defining a constant "INSTALL_PATH" and/or "INSTALL_URL" in a file that is included everywhere, which knows its relative location to the base url or file path, and does a simple string operation:
define('INSTALL_PATH', basename(__DIR__); // go one level up
You can access the properties of the $_SERVER superglobal variable.
echo $_SERVER['DOCUMENT_ROOT'];
The following, if located in "/foo/bar/foo/index.php", would echo /foo/bar/foo/.
Related
I am calling a function that reads $_SERVER['HTTP_HOST'] and render an anchor element with href that is read from $_SERVER['HTTP_HOST'].
On my mobile theme on Android devices this function appends a dot at the end of the url, so it looks like www.example.com. which makes some other functions work improperly.
Upon debugging I realized that it is precisely $_SERVER['HTTP_HOST'] that has this wrong value.
Anyone has this problem or any idea how to fix it?
i dont think its php issue, but this code can resolve your issue.
trim($_SERVER['HTTP_HOST'], '.')
In the Domain Name System, and most notably, in DNS zone files, a fully qualified domain name is specified with a trailing dot. For example,
somehost.example.com. specifies an absolute domain name that ends with an empty top level domain label.
So the PHP is actually returning the correct value. As to how to combat this, use sudhakar's suggestion.
I have a configuration file. This is not a stand-alone file. I will be including this file at the top of the pages that I want to use in, using require(). I want to dynamically get the complete absolute url path to this configuration file, regardless of it's location and store it as a constant within itself. For example:
Physical Location: (root dir)/my_folder/configuration.php
Need URL as: www.mydomain.com/my_folder/configuration.php
Physical Location: (root dir)/demos/my_folder/configuration.php
Need URL as: www.mydomain.com/demos/my_folder/configuration.php
Physical Location: (root dir)/demos/site1/my_folder/configuration.php
Need URL as: www.mydomain.com/demos/site1/my_folder/configuration.php
Physical Location: (root dir)/demos/site2/my_folder/configuration.php
Need URL as: www.mydomain.com/demos/site2/my_folder/configuration.php
Simple so far? Here's what really needed and makes it complicated (IMO). Consider this:
Config file located at: www.mydomain.com/demos/site2/my_folder/configuration.php
Have nested folders: www.mydomain.com/demos/site2/1/2/3/index.php
When I access the index.php file in the "3" sub-folder by following the URL above, I need the path to configuration file as www.mydomain.com/demos/site2/my_folder/configuration.php and not as www.mydomain.com/demos/site2/1/2/3/my_folder/configuration.php
How can I achieve the above?
If you can rely on the value of $_SERVER[ 'DOCUMENT_ROOT' ], then inside configuration.php:
$path = substr( __FILE__, strlen( $_SERVER[ 'DOCUMENT_ROOT' ] ) );
$url = "www.mydomain.com{$path}";
If it fits your use case, you can make it more dynamic using $_SERVER[ 'HTTP_HOST' ];
DOCUMENT_ROOT
I've used DOCUMENT_ROOT liberally in my development, as it's often the only dynamic variable available for constructing certain self-referential paths. There's a looong running Apache bug ticket (#26052) about how DOCUMENT_ROOT is poorly handled, particularly that Apache wouldn't allow you to set the value with RewriteRule and didn't set it to a sensible value when using mod_vhost_alias. The discussion goes on over a period of 7-8 years as people presumably from the Apache project resist changing the behavior, until they finally came around and made a change this year in 2.4.1. (I looked into this previously, but I forget now what the exact changes were, and how satisfying they are.)
If you look at the comments on the ticket you'll see people resisting changes to the behavior with comments like:
Don't trust the DOCUMENT_ROOT variable.
DOCUMENT_ROOT is not, never was, and never will be a reliable way of finding the filesystem path to web content.
So I suggest reading the comments on that ticket to see what people are saying the caveats of using it are. I've used it with a lot of success and don't know of a better way to achieve the same things in the same situations that DOCUMENT_ROOT is available and provides the necessary data.
What I used, which worked perfectly for what I wanted, was this:
define('URL', dirname(substr($_SERVER['SCRIPT_FILENAME'], strlen( $_SERVER[ 'DOCUMENT_ROOT' ] ) )).'/');
I would like to break up the url variable in Drupal 6 so I can place a directory name between the $base_url and the rest of the path. Any ideas as to how I could do this?
Thanks,
Jane
Well, it sounds like you already know the the $base_url, so the part you need is the internal path, which you can retrieve with $path = arg();.
However, I don't know what you hope to accomplish by doing this. Suppose you have a drupal URL like this:
http://www.example.com/node/76
That's actually an alias for THIS url:
http://www.example.com/index.php?q=node/76
The node/76 part is the internal drupal path, and the .htaccess file in the root folder cuts out the index.php?q= bit for a cleaner url.
So if you construct an URL like this:
http://www.example.com/directory/node/76
It will actually be pointing at:
http://www.example.com/index.php?q=directory/node/76
Which will then fail, because Drupal will try to treat directory/node/76 as an internal Drupal path, and not find it -- so you'll get a 404 error.
What are you trying to do?
Currently developing a PHP framework and have ran into my first problem. I need to be able to drop the framework into any folder on a server, no matter how many folders deep, and need to find that directory to use as a base URL.
For example, it currently works if I put the framework in the root of the server (http://cms.dev/), but if I were to put it in http://cms.dev/folder/ it does not work.
There are four existing answers, but they all seem to deal with file paths, and you're asking about a base URL for web requests.
Given any web request, you get a bunch of keys in $_SERVER that may be helpful. For example, in your mock example, you might have the following:
http://cms.dev/folder/ — $_SERVER['REQUEST_URI'] == /folder/
http://cms.dev/folder/index.php — $_SERVER['REQUEST_URI'] == /folder/index.php
http://cms.dev/folder/index.php/some/pathinfo — $_SERVER['REQUEST_URI'] == /folder/index.php/some/pathinfo
http://cms.dev/folder/some/modrewrite — $_SERVER['REQUEST_URI'] == /folder/some/modrewrite
Thinking critically, how would you pull out the base URL for any given subrequest? In certain cases you can look at $_SERVER['REQUEST_URI'] and strip off trailing elements if you know how deep in your hierarchy the request is. (For example, if your script is two folders deep, strip off the last two path elements.) When PATH_INFO or mod_rewrite are in use, things become less clear: as longer and longer URLs are provided, there is no clear indication where the paths end and the dynamic URL begins.
This is why WordPress, MediaWiki, phpBB, phpMyAdmin, and every application I've ever written has the user manually specify a base URL as part of the application configuration.
__FILE__ is a magic constant that returns the entire path of the current script. Combine with dirname and add ".." appropriately. It's more reliable than getcwd, since it cannot change during execution.
You can then strip off the web root, to get the relative path to your script (should map to URL). There are many $_SERVER variables that have this information. I suggest using the file system to determine:
If your script is publicly accessible?
At which depth / URL prefix?
Then combine with your base URL. If your script's path ==
/home/public/foo_1/script.php
... and your $_SERVER['DOCUMENT_ROOT'] ==
/home/public
Then you can rewrite your URL as /foo_1/script.php. You don't need the fully qualified URL, unless you want it. This technique works best if you execute it from a central location, like an autoloader.
In order to make urls work check the base tag:
<base href="http://cms.dev/folder/" />
If the PHP file paths are the issue go with Pestilance's advice:
dirname(__FILE__) // returns the directory of current file
Theres a bunch of useful stuff available for things like this in the $_SERVER array. Do a var_dump($_SERVER); to see which element(s) of the array you need.
dirname(__FILE__);
basename(__FILE__);
print_r($_SERVER);
pathinfo('www/htdocs/index.html');
realpath('../../dir1/');
parse_url('http://username:password#hostname/path?arg=value#anchor');
What you are looking for is the WEBROOT of your application based on your description. The checked answer is, by far, the closest answer.
The easiest way to identify the webroot is to have it be user defined, as was mentioned by Annika and noted in a comment.
However, there is a bit of information that was overlooked:
If you are trying to identify the location of the webroot, which coincidentally is also the top level of your framework, then you could use something like this:
$web_only_path = dirname($_SERVER['PHP_SELF']);
This will only work if your rewrite conditions are implemented correctly.
If they are in an htaccess file, no sweat.
However, if they are in an apache conf file. Then they must be contained within a container for the SERVER variable to store and return the proper information after working through the redirects when dealing with the SEO friendly URLs.
See:SCRIPT_NAME and PHP_SELF with mod_rewrite in .conf
To get the current path of the file you must use:
$path=getcwd();
This will return you if in windows for example C:\blah\blah\blah with no file name.
Sounds like you are looking for the relative path.
$_SERVER['SCRIPT_FILENAME']
should do the trick. The php.net site has good documentation on what is available to that http://php.net/manual/en/reserved.variables.server.php
Also, if you are ever curious about what else is there, and what the values are
<?php print_r($_SERVER); ?>
will tell you more that you thought you could know.
function GetCurrentWebDir() {
$CurrentPath = substr(
$_SERVER['SCRIPT_URL'], 0,
strlen($_SERVER['SCRIPT_URL']) - strlen(
strrchr($_SERVER['SCRIPT_URL'], "\\")
)
);
$CurrentFileName = basename(__FILE__);
return substr_replace(
$CurrentPath, '', -strlen($CurrentFileName),
strlen($CurrentFileName)
);
}
echo 'current dir:'.GetCurrentWebDir();`
cp:/apps/PHP/testtesttesttesttesttesttesttesttesttesttest.php
fn:testtesttesttesttesttesttesttesttesttesttest.php
len:48
current dir:/apps/PHP/
Use dirname(__PATH__) to fetch the parent directory path.
Is there any easy way to identify the file initially handling the request, ignoring get arguments and handling (at least basic) mappings like / to /index.php?
Ideally what I'm looking for is something like $_SERVER['REQUEST_URI'], except it returns the same value regardless of the get arguments and that value is the file requested, not the URI, nor the currently executing file ($_SERVER['PHP_SELF']). In other words, a $_SERVER['REQUESTED_FILE'] or something. I haven't seen anything like that. Does it exist, or do I need to write something manually?
Update
Here are some example URLs paired with what I would like the result to be:
example.com/mypage.php : /mypage.php
example.com/ : /index.php
example.com/foo/?hello=world : /foo/index.php
And these return values are true even in included files. See my answer below before answering, I think I've found what I was looking for.
I decided to test it out myself. The $_SERVER['SCRIPT_NAME'] variable serves up the path to the requested file, even if it's an index file, and without get parameters or anything else. The PHP documentation states this contains the path of the file, but it seems to be relative to the document root, just like PHP_SELF, but without the security vulnerability.
Here is the code I used to test this: https://gist.github.com/dimo414/5484870
The output when requesting example.com/?foo=bar:
__FILE__: /var/www/index.php
PHP_SELF: /index.php
SCRIPT_NAME: /index.php
REQUEST_URI: /?foo=bar
parse_url(REQUEST_URI): /
__FILE__: /var/www/pathtest.php
PHP_SELF: /index.php
SCRIPT_NAME: /index.php
REQUEST_URI: /?foo=bar
parse_url(REQUEST_URI): /
And the output when requesting example.com/index.php/<strong>XSS</strong>:
__FILE__: /var/www/index.php
PHP_SELF: /index.php/XSS # note the XSS exploit (this is bold in browser)
SCRIPT_NAME: /index.php # No exploit here
REQUEST_URI: /index.php/%3Cstrong%3EXSS%3C/strong%3E
parse_url(REQUEST_URI): /index.php/%3Cstrong%3EXSS%3C/strong%3E
__FILE__: /var/www/pathtest.php
PHP_SELF: /index.php/XSS
SCRIPT_NAME: /index.php
REQUEST_URI: /index.php/%3Cstrong%3EXSS%3C/strong%3E
parse_url(REQUEST_URI): /index.php/%3Cstrong%3EXSS%3C/strong%3E
As you can see, $_SERVER['SCRIPT_NAME'] always gives back the file that originally handled the request, i.e. the file in the URL, without any XSS risks.
$_SERVER['PHP_SELF']
Should return the actual script. But there are various methods.
I had a better link to a matrix of all the various file-related environment variables but I can't find it. I'll edit if it turns up.
Edit: I found a nice SO thread that details the differences between them.
Go get file name from the requested URL use following code.
basename($_SERVER['URL']);
basename($_SERVER['REQUEST_URI']);
basename($_SERVER['SCRIPT_NAME']);
basename($_SERVER['SCRIPT_FILENAME']);
basename($_SERVER['REQUEST_URI']);
basename($_SERVER['PATH_TRANSLATED']);
basename($_SERVER['PHP_SELF']);
use any one all all of those in the nested if condition so you will not miss file name any how.
parse_url($_SERVER['REQUEST_URI']) and then pathinfo($path) to get requested filename
$_SERVER['PHP_SELF'] to get real filename
$_SERVER['SCRIPT_NAME'] to get real filename
Its very old question and not very clear too.
What I understood is that you want to know which page is sending request GET/POST. This can be implemented by:
$_SERVER['HTTP_REFERER']
Now, to get the actual page name, write like:
= basename($_SERVER['HTTP_REFERER']);
This will solve you concern.