duanping5306 2013-09-12 03:35
浏览 17
已采纳

定义web根目录 - consant适用于包含但不重定向

I'm trying to create a constant which defines my web root dir, which I can use for constructing paths for requires, header redirects, images, etc.

I need the constant to work when used in files in the root folder and sub folders. I know I could easily hard code the paths with ../ etc, but the main reason I'm trying to get this to work (apart from clean code) is so I can re-use the code on various sites on different servers, where the path may vary.

my dir structure

/
  index.php
    /library
      libSetPathRoot.php

Document Root

echo $_SERVER["DOCUMENT_ROOT"];
Returns: /home/james/web/sites/
The "sites" dir contains various document roots defined in /etc/apache2/sites-available (so I can work on different scripts).

File contents

/index.php
require_once('library/libSetPathRoot.php'); //works fine.. of course

/library/libSetPathRoot.php
define("PATHROOT", realpath(__DIR__ .'/..').'/');

The above returns my root correctly:
echo PATHROOT;// /home/james/web/sites/site3/

I've tried the following and various other code to define a root path.
These, and others, didn't work for redirect(), include(), nothing at all:
define ('PATHROOT', getenv("DOCUMENT_ROOT"));
define ('PATHROOT', basename(dirname((__DIR__))));
echo PATHROOT;
Everything else seemed to return "site3" only.

The working define works for include() and require() regardless of where in the dir structure it is placed. ie if in file in sub dir to root calling root or other sub dir to root, in a file in root, included file etc.

But I just cannot get this working for header() redirect. Again, regardless of where I use it - root scripts, sub folder scripts, included scripts. Maybe I need another approach, but have read numerous options and tried them extensively (half a day spent).

Why is my define working for includes but not header redirect, and how can I make it work on all? Or do I have to use two methods, one for include and one for redirects?

Edit
Example header redirect I tried:
header('Location: '.PATHROOT.'page-not-found.php');
Returns a 404 for: /home/james/web/sites/site3/page-not-found.php
(the file does exist)

  • 写回答

2条回答 默认 最新

  • douyuan1752 2013-09-12 03:56
    关注

    You can't do such file redirection with header(). It sends HTTP headers to the browser which should be in browser accepted format. But you are sending some local(server) file path. Which is obviously not working. you have to send a url for redirection eg. header("Location: http://example.com/page-not-found.php")

    See the php documentation http://php.net/manual/en/function.header.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样