簡體   English   中英

如何使用頁面稍后定義的變量? PHP

[英]How can I use variables defined later in the page? PHP

這是我設置文件的方式:

index.php文件:

    include($sys->root_path.'sections/start.php'); // Includes everything from <html> to where we are now

    if (isset($_GET['page'])) {
      $page = $_GET['page'].'.php';
    } else {
      $page = 'index.php';
    }

    if (isset($_GET['cat'])) {
      $cat = $_GET['cat'];
    } else {
      $cat = '';
    }

    include($sys->root_path.'/content/'.$cat.'/'.$page);

    include($sys->root_path.'sections/end.php'); // Includes everything from here to </html>

要查看此頁面,請訪問: example.com/index.php?cat=red&page=car page= example.com/index.php?cat=red&page=car這將向我顯示一個頁面,其中包含文件內容:

/content/red/car.php

我遇到的問題是我想為每個頁面指定標題,元描述等,並且在start.php此特定頁面的任何特定數據之前,這會輸出到start.php頁面。

我希望做的是這樣的:

/CONTENT/RED/CAR.PHP:

<?php $page_title = 'Title of the page'; ?>
<p>Everything below is just the page's content...</p>

當所有數據都提取到該特定頁面的內容之前時,如何在網站的<head>中使用該特定於頁面的數據?

您可以執行以下操作:

switch($_GET['page']) {
    case 'car':
        // Here you could have another conditional for category.
        $page_title = 'Title of the page';
        break;
    // Other cases.
}
include($sys->root_path.'sections/start.php');

在start.php中,您可能會遇到類似以下內容的情況:

<title><?php echo $page_title; ?></title>

我必須建議不要包含內容。 這是不安全的。 有人可以瀏覽您的服務器文件或包含您不想包含的內容。 除非一個人總是通過正則表達式或其他方式過濾該變量,否則永遠不要以這種方式包含文件(通過獲取變量)。

正確的方法是使用數據庫和apache url_rewrite。 我的回答只是解決您的問題。


第1步

if statment之下包含start.php ,這樣,當您包含start.php時,您已經知道所需的頁面,如下所示:

if (isset($_GET['page'])) {
  $page = $_GET['page'].'.php';
} else {
  $page = 'index.php';
}

if (isset($_GET['cat'])) {
  $cat = $_GET['cat'];
} else {
  $cat = '';
}

include($sys->root_path.'sections/start.php');

第2步

現在,在start.php使用開關:

<?php
switch ($cat) {
    case "blue":
        $title = "The car is $page";
        break;
    case "green":
        $title = "The car is $page";
        break;
    case "red":
        $title = "The car is $page";
        break;
    default:
        $title = "Welcome to ...";
} 
?>

    <!DOCTYPE html>
    <head>
    <title><?php echo $title ?></title>
    </head>
etc...

我的建議是將MVC方法與函數一起使用以通過setter函數傳遞參數或OOP。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM