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.
Related
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/.
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' ] ) )).'/');
How can I alter url or part of it using php? I lost the code that I have used and now I cannot find answer online.
I know using header('Location: www.site.com') gets redirect but how can I just show fake URL?
I don't want to use mod_rewrite now.
It is impossible in PHP, which is executed server side. Any change to the url you make will trigger a page loading.
I think it may be possible in javascript, but I really doubt this is a good idea, if you want to rewrite an url only in the user adressbar, you're doing something wrong, or bad ;)
What you've actually asked for isn't possible in using PHP (Although, in JavaScript you can use the dreadful hashbang or the poorly supported bleeding edge pushState).
However, in a comment on another answer you stated that your goal is actually friendly URIs without mod_rewrite. This isn't about showing a different URI to the real one, but about making a URI that isn't based on a simple set of files and directories.
This is usually achieved (in PHP-land) with mod_rewrite, so you should probably stick with that approach.
However, you can do it using ScriptAlias (assuming you use Apache, other webservers may have different approaches).
e.g. ScriptAlias /example /var/www/example.php in the Apache configuration.
Then in the PHP script you can read $_SERVER['REQUEST_URI'] to find out what is requested and pull in the appropriate content.
You can make somewhat SEO-friendly URLs by adding directories after the php script name so that your URLs become:
http://yoursite.com/script.php/arg1/arg2
In script.php:
<?php
$args = preg_split('#/#', $_SERVER['PATH_INFO']);
echo "arg1 = ".$args[1].", arg2 = ".$args[2]."\n";
?>
if you use some more htaccess trickery, then you can make the script.php look like something else (see #David's answer for an idea)
You can try using,
file_get_contents("https://website.com");
This is not going to redirect but fire the api and you can catch the output by assigning a variable to above function.
So I have a .htaccess file which is performing a rewrite from /testscript1.php/testvar1/testvar2 to
/testscript2.php/testvar3/testvar4
(this is an over simplification but you get the idea).
Now though in my testscript2.php script when i access the $_SERVER['REQUEST_URI'] variable i see /testscript1.php/testvar1/testvar2 rather than /testscript2.php/testvar3/testvar4 which is what I am looking for. i.e $_SERVER['REQUEST_URI'] contains the uri before the rewrite.
My question is simply, is there a way to access the rewritten uri?
Try using phpinfo() to get a view on what $_SERVER looks like on a rewritten page. Apache supplies quite a lot of info that may be useful.
On my test server, I get the following which may help you:
$_SERVER["REDIRECT_QUERY_STRING"]
$_SERVER["REDIRECT_URL"]
$_SERVER["QUERY_STRING"]
$_SERVER["REQUEST_URI"]
$_SERVER["SCRIPT_NAME"]
$_SERVER["PHP_SELF"]
I would expect that at least one or a combination of those should be able to reliably give you the information you're looking for.
Cheers.
If you’re using the path info to pass an additional path, you can strip that suffix from PHP_SELF:
substr(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH), -strlen($_SERVER['PATH_INFO']))
Or simply use SCRIPT_NAME since PHP_SELF = SCRIPT_NAME + PATH_INFO. Just take a look at the various values in $_SEVER.
lets say i want to go to
http://example.com/something/a/few/directories/deep
is there a way I can process this in PHP without having to make those directories? I just want to get everything after the domain name as a variable and work from there.
The most common way of doing this is by using mod_rewrite. (There in an introduction to this at http://articles.sitepoint.com/article/guide-url-rewriting). This allows you to internally map these friendly URLs to query parameters passed to your PHP script.
Sure. You don't even need mod_rewrite if the beginning is constant or has only a few possible values. Make a php file named something (no extension) and tell Apache (via a SetHandler or similar directive) to treat it as PHP. Then, examine $_SERVER['PATH_INFO'] in the script, which will look like a/few/directories/deep IIRC. You can use that to route your request however you like.
Alternatively. as Martin says, use a simple mod_rewrite rule to rewrite it to /dispatch.php/something/a/few/directories/deep and then you have the whole path in PATH_INFO.
You do not need mod_rewrite to handle such a scenario. Most of the popular PHP frameworks currently support URI segment parsing. This is a simple example which still leaves a few security holes to be patched up.
You could handle this by taking one of the global $_SERVER variables and splitting it on forward slashes like so:
if (!empty($_SERVER['REQUEST_URI'])) {
$segments = explode('/', $_SERVER['REQUEST_URI']);
}
The $segments variable will now contain an array of segments to iterate over.
Assuming you are using apache...
Add a re-write rule (in your vhost conf or just drop .htaccess file in you doc root), to point everything to index.php. Then inside of your index.php, parse the request uri and extract path
RewriteEngine on
RewriteRule ^.*$ index.php [L,QSA]
index.php:
$filepath = $_SERVER['REQUEST_URI'];
$filepath = ltrim($myname, '/'); //strip leading slash if you want.
This actually is not a PHP5-related quesion - URL rewriting is part of your webserver.
You can, when you use mod_rewrite on Apache (don't know about IIS, but there likely is something similar).