嗨,
我從 PHP 開始,并創建了我的網站。我創建了一個頁眉和頁腳的組件,以在每個頁面上列印:require '/assets/components/header.php';和require '/assets/components/footer.php';
所以,問題是在本地主機上,它可以作業,但在網站上,它沒有作業,我有一個 http 錯誤 500
劇目: 檔案夾樹
我嘗試:
1.不同型別的鏈接
require 'assets/components/header.php';
require './assets/components/header.php';
require '../assets/components/header.php';
2.創建一個變數 $BASE_URL 來存盤網站的 url 并像這樣要求:require "$BASE_URL/assets/components/header.php";。我將設定 'allow_url_include' 設定為 true,但出現此錯誤:
[04-Nov-2021 12:28:40 UTC] PHP Warning: require(http://#####/assets/components/header.php): Failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
'#####' -> 我的網站
我讀過一個主題,將 'allow_url_include' 設定為 true 是不安全的,所以如果我們可以做不同的事情。
頭檔案
<?php
require_once "$BASE_URL"."assets/function.php";
if(!isset($title)){
$title='Error 404 - Catif';
}
if(!isset($page)){
$page='error';
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href='/assets/css/style.css'>
<title><?= $title ?></title>
</head>
<body>
<nav>
<div class="nav-left"><p class="nav-name">Catif</p></div>
<div class="nav-right">
<a class="nav-item <?php if($page === 'home'): ?>active<?php endif ?>" href="/index.php">Projets</a>
<a class="nav-item ml-80 <?php if($page === 'me'): ?>active<?php endif ?>" href="views/me.php">Moi</a>
<a class="nav-item ml-80 <?php if($page === 'contact'): ?>active<?php endif ?>" href="/views/contact.php">Contact</a>
</div>
<button class="nav-button">==</button>
</nav>
<div class="container">
uj5u.com熱心網友回復:
在 PHP 中包含組件檔案時,您應該使用檔案路徑,而不是 URL。例如,我們可以使用相對檔案路徑將標題包含在 中pageOther1.php,應該是這樣的。
require "../../../assets/components/header.php";
// OR
require __DIR__ . "/../../assets/components/header.php";
為了提高效率,特別是如果您要包含多個組件并具有不同級別的嵌套視圖,您可以functions.php在 PHP 檔案(例如initialize.php或config.php)中定義頁眉和頁腳路徑(并包括任何其他全域腳本,例如)您的應用程式的根目錄。這樣你只需要initialize.php使用 PHP 常量來要求和包含你想要的組件。
這是一個更有效的方法
initialize.php在根目錄下的 PHP 檔案(例如)中將組件路徑定義為常量
define("APP_PATH", dirname(__FILE__)); // The main project directory
define("HEADER", "APP_PATH" . "/assets/components/header.php"); // Path to header.php
define("FOOTER", "APP_PATH" . "/assets/components/footer.php"); // Path to footer.php
// You could also include your global scripts here and don't have to include it on each view page
require "APP_PATH" . "/path_to_global_script.php";
然后在視圖中包含組件和腳本。一個例子pageOther1.php是:
require "../../../initialize.php"; // Path to the file which defines the constants
require HEADER;
// Page content
require FOOTER;
您可以輕松地為多個組件和函式腳本擴展它。
uj5u.com熱心網友回復:
不要將 BASE_URL與必需/包含的檔案一起使用。使用類似__DIR__或$_SERVER['DOCUMENT_ROOT']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348200.html
