我想让通用的页眉/页脚包含文件。
这里的通用是指当从“includes”目录调用“header.php”时,无需在任何更深层次添加“../”,即可应用于任何目录级别的文件中。
好吧,好吧。
我可以用
<?php include $_SERVER[‘DOCUMENT_ROOT’].”/includes/header.php”;?>
除了图像包含对.css文件的相对引用,而.css文件包含其相对引用(例如“background:url(../ header.php /o.gif);”),所有这些都会使我在每个新级别陷入“../../”的泥潭。
当然,我可以在每个级别复制.css和../图像,但这看起来有点笨拙,与伟大的php (在一个地方控制所有内容)的原则和精神背道而驰。
尊敬的你自己
发布于 2012-02-10 01:38:32
您可以让CSS中的url是一个绝对路径(以/开头的路径)。然后,无论用户在您的网站上浏览过什么,它都将正常工作。
或者,您可以使用URL重写mod_rewrite来使用户访问的URL保持在顶层。
发布于 2012-02-10 02:13:36
调用css图像之类的用法../而在编程上是正确的,这是错误的形式。您应该始终使用绝对路径/css/style.css /images/image.png /js/script.js等...
我通常使用页眉和页脚常量来定义应用程序目录。
define('APPDIR', $_SERVER['DOCUMENT_ROOT']);这使得包含其他文件变得更容易,而不必一遍又一遍地写出文档根目录的所有变量。
虽然在我看来,一切都在向框架发展,但你真的应该考虑一下sung Symfony、Codeigniter或类似的东西。如果这是一个3页的交易,直接用php就可以了,但是如果你在做一个全力以赴的应用,而且是新开发的,你不使用框架就是害了自己。
发布于 2012-02-10 02:54:44
您希望封装变化的内容,即请求的某个位置(从浏览器查看)到网站的根URL (再次从浏览器查看)的相对路径。
为此,您首先需要知道根URL和请求的URL,在PHP中可能是这样的:
$rootURL = 'http://example.com/mysite/basedir/';
$requestURI = $_SERVER['REQUEST_URI']; # e.g. /mysite/basedir/subdir/index.php然后PHP提供了不同的字符串函数来将其转换为相对路径:
'../' + X例如,您可以将其放入执行此操作的类中:
$relative = new RelativeRoot($rootURL, $requestURI);
echo $relative; # ../
echo $relative->getRelative('style/default.css'); # ../style/default.css这样的类的一个例子是:
/**
* Relative Path to Root based on root URL and request URI
*
* @author hakre
*/
class RelativeRoot
{
/**
* @var string
*/
private $relative;
/**
* @param string $rootURL
* @param string $requestURI
*/
public function __construct($rootURL, $requestURI)
{
$this->relative = $this->calculateRelative($rootURL, $requestURI);
}
/**
* @param string $link (optional) from root
* @return string
*/
public function getRelative($link = '')
{
return $this->relative . $link;
}
public function __toString()
{
return $this->relative;
}
/**
* calculate the relative URL path
*
* @param string $rootURL
* @param string $requestURI
*/
private function calculateRelative($rootURL, $requestURI)
{
$rootPath = parse_url($rootURL, PHP_URL_PATH);
$requestPath = parse_url($requestURI, PHP_URL_PATH);
if ($rootPath === substr($requestPath, 0, $rootPathLen = strlen($rootPath)))
{
$requestRelativePath = substr($requestPath, $rootPathLen);
$level = substr_count($requestRelativePath, '/');
$relative = str_repeat('../', $level);
# save the output some bytes if applicable
if (strlen($relative) > strlen($rootPath))
{
$relative = $rootPath;
}
}
else
{
$relative = $rootPath;
}
return $relative;
}
}https://stackoverflow.com/questions/9215791
复制相似问题