繁体   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