PHP Header Location: ../location vs $_SERVER[DOCUMENT_ROOT]/location

本小妞迷上赌 提交于 2019-12-12 03:39:49

问题


So, I made a simple PHP login, but when I tried to redirect like this:

$path = $_SERVER["DOCUMENT_ROOT"];  
header("Location: $path/admin/index.php");

it seemed like it did nothing, but after I refreshed the page I was logged in.
After I changed my code to this:

header("Location: ../admin/index.php");

it works.

Could someone please explain this to me?

Ps. sorry for my bad english


回答1:


The header is sent to the browser, so it is not an internal server maneuver. And with it not being an internal redirect, you don't deal with internal paths. When you use DOCUMENT_ROOT you will get the internal server path to the directory where your files are located.

If you want to reference the root of the site as a URL, just use /.

header("Location: /admin/index.php");
header("Location: /"); # go to homepage, for example

Your .. worked because you probably were on a subdirectory, and .. was translated to the parent directory which is where admin is.




回答2:


$_SERVER["DOCUMENT_ROOT"]; 

returns path like /var/www/html/yourfolder/, but you have to redirect to website.com/yourfolder/ or localhost/yourfolder/.

hence that won't work.




回答3:


Have you tried printing the value of $path?

the value of $path is relative to the actual file location

e.g. $path = '/c/inetpub/sites/example/main/'

You probably wanted something like '/c/inetpub/sites/example/' or '/c/inetpub/sites/example/main/..'



来源:https://stackoverflow.com/questions/41379727/php-header-location-location-vs-serverdocument-root-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!