gpt4 book ai didi

php - 在 PHP 中设置正确路径的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:41 27 4
gpt4 key购买 nike

我正在开发一个 PHP MVC 框架,我刚刚发现的问题是目录中特定文件的路径。当我路由到呈现页面的函数时,模板文件中定义的所有文件(包括 CSS 和图像)都没有加载。

这是我的文件夹结构

  • 系统
    • 控制者
    • 模特
    • 核心
    • 配置
    • 模板
      • 首页
        • CSS
          • 样式.css
        • 图片
        • js
        • home.php
    • 初始化文件
  • .htaccess
  • index.php

首先,我用这段代码在前端 Controller index.php 中设置了路径:

<?php
// Path to system
$system_path = str_replace('\\', '/', dirname(__FILE__)).'/system';
$template_path = $system_path.'/templates';
?>

就像任何其他 php 框架一样,我可以在整个框架中使用这些路径变量。所以在我的主页模板文件 (system/templates/home/home.php) 中,我有调用位于 system/templates/home/css/style.css 中的 style.css 的标签。所以我在模板文件中的链接标签是

<link rel='stylesheet' type='text/css' href='<?= $template_path; ?>/home/css/style.css' />

当我呈现页面时,上面 css 文件的绝对路径正确显示为

C:/Appserv/www/mysite/system/templates/home/css/style.css

但样式表从未加载,我也不知道为什么。当我单击指向 css 文件的链接时,它会返回 403 错误以及这样的奇怪路径

You don't have permission to access      /mysite/C:/AppServ/www/mysite/system/templates/home/css/style.css 

这让我感到困惑,因为此时路径不正确,因为它以网站名称开头,后跟上面模板文件中定义的路径。

有什么办法可以解决这个问题吗?

最佳答案

将 CSS 文件加载到您的网页时,您不需要系统文件路径,而是 URL。所以代替:

<link rel='stylesheet' type='text/css' href='<?= $template_path; ?>/home/css/style.css' />

你需要这样的东西:

<link rel='stylesheet' type='text/css' href='/home/css/style.css' />

或者,如果您定义了基本 URL:

<link rel='stylesheet' type='text/css' href='<?= $base_url; ?>/home/css/style.css' />

如果您仍想访问本地文件,请考虑改用 file:/// 协议(protocol)(不推荐)。

关于php - 在 PHP 中设置正确路径的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27998004/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com