php relative paths and directories

假装没事ソ 提交于 2019-12-03 21:09:14
action='/ProjectName/helpers/login.php'

Assuming your root is http://localhost then the above link should always resolve to http://localhost/ProjectName/helpers/login.php whether it's called from http://localhost/ProjectName/index.php or http://localhost/ProjectName/subdir/index.php

If you don't want to hardcode "ProjectName" into many different scripts, you can use a global variable and define it in a config file:

helpers/ConfigOptions.php:

<?php
$ProjectName = "ProjectName";
?>

Then in your scripts, include the config file and use the variable you defined:

index.php:

include $_SERVER['DOCUMENT_ROOT'] . '/helpers/ConfigOptions.php';

...

echo "
  <form action='/$ProjectName/helpers/login.php'>
  ....
";

More about DOCUMENT_ROOT:

DOCUMENT_ROOT is defined in the server configuration file and is the root on the filesystem of where scripts are executing, not the web address you would type in a browser. In the above example, I'm assuming that document root looks something like /home/user/www/ProjectName. If DOCUMENT_ROOT is only /home/user/www then you can change your include path to this:

include $_SERVER['DOCUMENT_ROOT'] . '/ProjectName/helpers/ConfigOptions.php';

or use a relative path. My vote would be on the latter since you wouldn't need to hardcode "ProjectName".

So include() and require() would take either:

  1. An absolute path to the file
  2. A path that's relative to the current executing script. If A includes B and B includes C, when B includes C it needs to provide a path that is relative to A.

So when do you need to use DOCUMENT_ROOT? Usually with templates where a relative path like ../helpers/file.php can resolve to different absolute paths depending on what's including the file. In the above example where index.php is including ConfigOptions.php, you probably don't need to use DOCUMENT_ROOT since index.php is not a template. I used it anyway to be safe, but maybe I opened up a whole can of worms here. I hope I didn't confuse you even more.

If you have a link that starts with a slash it always gets appended to the root and not your current directory...

So if your page is www.example.com/mySite/foo.html and you have a link like this: <a href="/bar.html">Bar/<a> the user will get redirected to www.example.com/bar.html ...

You should just have your form action point to helpers/login.php

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