In HTML you can set your href to "/folder/page" and the starting / would go to the root-directory of your web application (meaning it would start at www.yoursite.com) and move on from there.
Now, in PHP, can i do this? I am having a problem, since i have a file, that ALWAYS needs to start at the root, and then go a folder down. I can't use relative paths, since it will be included in other pages and of thus, i wouldn't know how many layers to go up before i was in the root directory.
I tried using "$_SESSION['DOCUMENT_ROOT']" but that gives me an address too far up the directory tree. For example (on a test site) i have this URL:
http://localhost:8888/kasseNet-BitBucet/
And i want THAT to be my root. Currently it's something like "Applications/Mamp/htdocs".
How can i achieve this? Obviously i could use an absolute path for this, but then it wouldn't be easy for me to launch it, since i would have to change it to not be on a localhost environment.
I have been googling my ass off, but i can't seem to find the right fit. It should be an easy task to accomplish.
For completeness sake, here is my structure:
(assuming we are in "root" - the localhost htdocs/site folder)
- Login
*Authenticate.php
*login.php
- Other
*test.php
- default.php
Now, both "default.php" and "test.php" will include the authenticate.php. The authenticate.php will redirect to the login.php. Now, the problem is that if i include it in the default.php, my path in the Authenticate.php file to the login.php would be "Login/Authenticate.php". BUT, if i include it in the test.php, i would have to do "../Login/Authenticate.php". This illustrates the problem, and it only gets worse as the structure grows.
As you can imagine, it is for a login script where i include the authenticate file, that will redirect to the login page if the user is not logged in. All the examples i've found though, just uses a flat structure with no extra directories, so they don't have that problem.
Hoping for some help, been stuck for days thinking of a solution xD
Thank you in advance.
Best Regards
/JBJ
Use this to get the root URL and append whatever you want after it.
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
If your path is something like http://localhost:8888/kasseNet-BitBucet/path1/path2/index.php you have to define kasseNet-BitBucet as your root directory. PHP cannot undrestand that kasseNet-BitBucet is your root directory and path1 for example is not.
So:
$my_root_dir = 'kasseNet-BitBucet';
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/' . $my_root_dir;
Related
So I've been using StackOverflow for programming related topics for over 5 years and never once considered registering as 9/10 times I come on, I find what I am looking for. This time, I've trawled the internet, the suggestions from stack overflow, and I can't find the answer, so here I am.
I'm looking to #include a navigation bar to make it universally accessible no matter what page the user is on. The problem is, I have multiple directories, /login
/register
/profile
The list goes on, of course for things such as CSS files, navigation and JS files. I don't want to constantly have to define the href to be '../' or '../../' of a file. That is an insane amount of maintenance for what soon will be a vast directory of PHP files.
The problem I'm having is trying to calculate how I can detect which directory the user is in via the #include file, and if they wish to return home for example, ensuring the correct amount of change directories occur.
I hope I'm making sense here.
I believe I may require the use of $_SERVER but I'm genuinely stuck on even providing code I've attempted to work on. I'm not expecting a hand out, but more an explanation.
Thanks
This is my first attempt, it works to a degree but it's dependent on the page I originally tested the code on. The echo's is simply to see what is going on myself in the background.
This is incredibly easy to perfect using the Laravel framework but doing it normally for some reason I've struggled with it.
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'index.php';
$folder = $uri;
$folder = "/Folder1/Folder2/Folder3/Folder4/Folder5";
echo substr_count($folder, "/");
echo '<br>' . $folder . '<br>';
$EndLoop = substr_count($folder, "/");
$String = '';
for($Loop = 1; $Loop < $EndLoop; $Loop ++)
{
echo $Loop;
$String = '../' . $String;
echo '<br>';
echo $String;
}
EDIT 2:
I've just worked this which typically works.. I realized when using a
Sign Up
Was routing it to host/directory_currently_in/signup/
So what I have done is this
<?php $host = $_SERVER['HTTP_HOST'];
//further down
echo 'Sign Up';
Because the signup directory is in the root directory and the individual may be 3 directories further in than the root, I had to try find a way to root them right back up 2 or 3 folders back into the sign up directory.
Using http:// and linking to the host has done this for me. Any suggestions on improvements?
Try something along the lines of:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>
That way you are always referring to the base and then building the folder structure from there.
i have developed a php application which is running perfect on local server. when i deployed the application on web server the links are not working
1) my site is "abc.myapplication.com" (abc is subdomain)
i defined following variable in config file
define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);
ROOT_PATH variable shows /home/punjabfo/public_html/abc (which is perfect)
for link i used following code
Add Record
link should go to "abc.myapplication.com/addrecord.php" but link go to
"abc.myapplication.com/home/punjabfo/public_html/abcaddrecord.php"
i tried a lot but could not fin the issue. please help. thanks
What is wrong with Keeping It Simple
Add Record
Let the server do all the work, as it gets it right and you do less messing around.
Try
define('ROOT_PATH', $_SERVER['HTTP_HOST']);
Just use
Add Record
You can try -
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.parse_url($url, PHP_URL_HOST) . '/';
Your issue is "$_SERVER['DOCUMENT_ROOT']". $_SERVER['DOCUMENT_ROOT'] stands for the root directory on the server (dir-path). What you need, is the URL and not the file-system-path.
Take a look on
<?php
echo "<pre>";
var_dump($_SERVER);
echo "</pre>";
?>
Why not to do
Add Record
Of course you do not need ROOT_PATH in the URL. What you do is returning full path of the file, instead of link. And btw, full path is incorrect itself, as you forgot slash before addrecord.php.
So, I've found a way to get the current directory using dirname(__FILE__) and getting the domain with $_SERVER['HTTP_HOST']. While both of these are well and good, they aren't quite what I need them to be.
For instance, if I have a script on http://mydomain.com/scripts/myscript.php, I'd like to get http://mydomain.com/scripts/. I feel like there should be an easy way to do this and that I've somehow overlooked something.
As an aside, I am currently using the script in a cloud shared hosting environment, so the directory structure is somewhat odd.
Try:
<?php
echo $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
The only problem with that is that dirname returns the parent directory, so if you access http://domain.com/scripts/ directly you'll just get http://domain.com/ withouth the scripts. http://domain.com/scripts/script.php resolves correctly to http://domain.com/scripts/ though.
Try:
<?php
echo $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
function url_part(){
$http=isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$part=rtrim($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME']));
$domain=$_SERVER['SERVER_NAME'];
return "$http"."$domain"."$part";
}
echo url_part;//htts://www.example.net/test
I am back with a simple question (or related question).
The question is simple however I have not received an answer yet. I have asked many people with different experience in PHP. But the response I get is: "I don't have any idea. I've never thought about that." Using Google I have not been able to find any article on this. I hope that I will get a satisfying answer here.
So the question is:
What is the difference between $_SERVER['DOCUMENT_ROOT'] and $_SERVER['HTTP_HOST'] ?
Are there any advantages of one over the other?
Where should we use HTTP_HOST & where to use DOCUMENT_ROOT?
DOCUMENT_ROOT
The root directory of this site defined by the 'DocumentRoot' directive in the General Section or a section e.g.
DOCUMENT_ROOT=/var/www/example
HTTP_HOST
The base URL of the host e.g.
HTTP_HOST=www.example.com
The document root is the local path to your website, on your server; The http host is the hostname of the server. They are rather different; perhaps you can clarify your question?
Edit:
You said:
Case 1 : header('Location: '. $_SERVER['DOCUMENT_ROOT'] . '/abc.php')
Case 2: header('Location: '. $_SERVER['HTTP_HOST'] . '/abc.php')
I suspect the first is only going to work if you run your browser on the same machine that's serving the pages.
Imagine if someone else visits your website, using their Windows machine. And your webserver tells them in the HTTP headers, "hey, actually, redirect this location: /var/www/example/abc.php." What do you expect the user's machine to do?
Now, if you're talking about something like
<?php include($_SERVER['DOCUMENT_ROOT'] . '/include/abc.php') ?>
vs
<?php include($_SERVER['HTTP_HOST'] . '/include/abc.php') ?>
That might make sense. I suspect in this case the former is probably preferred, although I am not a PHP Guru.
<?php include($_SERVER['DOCUMENT_ROOT'] . '/include/abc.php') ?>
should be used for including the files in another file.
header('Location: '. $_SERVER['HTTP_HOST'] . '/abc.php')
should be used for hyperlinking
Eh, what's the question? DOCUMENT_ROOT contains the path to current web, in my case /home/www. HTTP_HOST contains testing.local, as it runs on local domain. The difference is obvious, isn't it?
I cannot figure out where you could interchange those two, so why should you consider advantages?
HTTP_HOST will give you URL of the host, e.g. domain.com
DOCUMENT_ROOT will give you absolute path to document root of the website in server's file system, e.g. /var/www/domain/
Btw, have you tried looking at PHP's manual, specifically $_SERVER? Everything is explanied there.
if you want domain path like 'example.com', you can use "HTTP_HOST"
if you want folder '/public_html/foldername/' path you can use
"DOCUMENT_ROOT"
$_SERVER ['HTTP_HOST'] is defined by the client and may not even be set! You can repeat a request and withhold the header for local testing in developer tools such as for Waterfox/Firefox. You must determine if this header is set and if the host being requested exists (one of the very first things you do, even before starting to send any of your headers) otherwise the appropriate action is to kill the entire process and respond with an HTTP 400 Bad Request. This goes for all server-side programming languages.
$_SERVER['DOCUMENT_ROOT'] is defined by the server as the directory which the executing script is located. Examples:
public_html/example.php = public_html/
public_html/test1/example.php = public_html/test1/
Keep in mind that if you're using Apache rewrites that there is a difference between the $_SERVER['REQUEST_URI'] (the URL requested) and $_SERVER['PHP_SELF'] (the file handling the request).
The Title question is perfectly awnsered by John Ledbetter.
This awnser is intended to expand and offer additional information about what seems to be the original poster inner concerns:
Where would make sense to use the URL based location: $_SERVER['HTTP_HOST'] ?
Where would make sense to use the local based location: $_SERVER['DOCUMENT_ROOT'] ?
Where both can be used, what are the Advantages and Disadvantages of each one. ?
Following my awnsers:
By usign the HTTP_HOST you can abstract yourself from the machine Folder System which means in cases where portability is a concern and you are expected to install the Application on multiple servers potentially with diferent OS this approach could be easier to maintain.
You can also take advantage of HTTP_HOST if your server is going to become unavailible and you want a diferent one from the cluster to handle the request.
By Using the DOCUMENT_ROOT you can access the whole filesystem (depends on the permissions you give to php) it makes sense if you want to access a program which you dont want to be accesible from the web or when the Folder System is relevant to your Application.
You can also take advantage of DOCUMENT_ROOT to get the subsite root instead of the Host.
$_SERVER['HTTP_HOST'] = "www.example.com";
$_SERVER['DOCUMENT_ROOT'] = "var/www/domain/subsite1" // equivalent to www.example.com/subsite1
$_SERVER ['HTTP_HOST'] returns the domain url
a.g. www.example.com
While $_SERVER['DOCUMENT_ROOT'] returns the roof of current web..
Such as
Other answers have alluded to it, but I wanted to add an answer just to be sharp as a grizzly bear tooth in one point - don't trust $_SERVER['HTTP_HOST'] as safe where following code does:
<?php
header('Location: '. $_SERVER['HTTP_HOST'] . '/abc.php');
#Or
include($_SERVER['HTTP_HOST'] . '/include/abc.php');
?>
The variable is subject to manipulation by the incoming request and could contribute to an exploit. This may depend on your server configuration, but you don't want something filling out this variable for you :)
See also:
https://security.stackexchange.com/questions/32299/is-server-a-safe-source-of-data-in-php
https://expressionengine.com/blog/http-host-and-server-name-security-issues
I'm trying to dynamically detect the root directory of my page in order to direct to a specific script.
echo ($_SERVER['DOCUMENT_ROOT']);
It prints /myName/folder/index.php
I'd like to use in a html-file to enter a certain script like this:
log out
This seems to be in bad syntax, the path is not successfully resolved.
What's the proper approach to detect the path to logout.php?
The same question in different words:
How can I reliably achieve the path to the root directory (which contains my index.php) from ANY subdirectory? No matter if the html file is in /lib/subfolder or in /anotherDirectory, I want it to have a link directing to /lib/logout.php
On my machine it's supposed to be http://localhost/myName/folder (which contains index.php and all subdirectories), on someone else's it might be http://localhost/project
How can I detect the path to application root?
After some clarification from the OP it become possible to answer this question.
If you have some configuration file being included in all php scripts, placed in the app's root folder you can use this file to determine your application root:
$approot = substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']));
__FILE__ constant will give you filesystem path to this file. If you subtract DOCUMENT_ROOT from it, the rest will be what you're looking for. So it can be used in your templates:
log out
Probably you are looking for the URL not the Path
log out
and you are not echoing the variable in your example.
Your DOCUMENT_ROOT is local to your machine - so it might end up being c:/www or something, useful for statements like REQUIRE or INCLUDE but not useful for links.
If you've got a page accessible on the web - linking back to a document on C: is going to try and get that drive from the local machine.
So for links, you should just be able to go /lib/logout.php with the initial slash taking you right to the top of your web accessible structure.
Your page, locally - might be in c:/www/myprojects/project1/lib/logout.php but the site itself might be at http://www.mydomain.com/lib/project.php
Frameworks like Symfony offer a sophisticated routing mechanism which allows you to write link urls like this:
log out
It has tons of possibilities, which are described in the tutorial.
Try this,
log out
This jumps to the root directly.
DOCUMENT_ROOT refers to the physical path on the webserver. There is no generic way to detect the http path fragment. Quite often you can however use PHP_SELF or REQUEST_URI
Both depend on how the current script was invoked. If the current request was to the index.php in a /whatever/ directory, then try the raw REQUEST_URI string. Otherwise it's quite commonly:
<?= dirname($_SERVER["SCRIPT_NAME"]) . "/lib/logout.php" ?>
It's often best if you use a configurable constant for such purposes however. There are too many ifs going on here.
I'm trying to figure this out for PHP as well. In asp.net, we have Request.ApplicationPath, which makes this pretty easy.
For anyone out there fluent in PHP who is trying to help, this code does what the OP is asking, but in asp.net:
public string AppUrl
{
get
{
string appUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if (appUrl.Substring(appUrl.Length - 1) != "/")
{
appUrl += "/";
}
// Workaround for sockets issue when using VS Built-int web server
appUrl = appUrl.Replace("0.0.0.0", "localhost");
return appUrl;
}
}
I couldn't figure out how to do this in PHP, so what I did was create a file called globals.php, which I stuck in the root. It has this line:
$appPath = "http://localhost/MyApplication/";
It is part of the project, but excluded from source control. So various devs just set it to whatever they want and we make sure to never deploy it. This is probably the effort the OP is trying to skip (as I skipped with my asp.net code).
I hope this helps lead to an answer, or provides a work-around for PHPers out there.