1

我有一个应用程序,我在其中创建了一个应用程序中header.php的所有页面显然很常见的应用程序,我将其包含在所有其他页面的顶部。该头文件包含htmlhead标签和DOCTYPE声明等以及每个页面所需的一些常见的JS和CSS文件。但是根据页面,我想包含一些特定的文件。

header.php现在,我如何根据请求的 url 包含特定的 JS 或 CSS 文件。

我试图$_SERVER['PHP_SELF']在头文件的顶部使用来获取 url,但它不起作用。

请建议在这种情况下应该使用的最佳技术。

示例代码

header.php

 <?php
 include (dirname(__FILE__) . "/includes/functions.php");
 $url = $_SERVER['REQUEST_URI'];
  ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>My APP</title>
<meta charset="utf-8" />
<meta name="robots" content="noodp, noydir" />
<meta http-equiv="X-Frame-Options" content="deny" />
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/main.js"></script>
<?php
if($url == "teachers.php"){
echo "<script src='js/teachers.js'></script>";
   }  
?>

</head>
<body>
4

3 回答 3

3

The array you are looking for is the superglobal $_SERVER. It has all that info. More specifically: $_SERVER['REQUEST_URI'].

$_SERVER['REQUEST_URI'] gives the complete path, including slashes and any GET request. In your case (if teachers.php is in your server's root, and you don't GET anything), it will hold /teachers.php, and you are comparing against teachers.php.

$_SERVER['SCRIPT_FILENAME'] gets the executing script, which is what you seem to be looking for.

You could use basename to filter the path out:

$url = basename($_SERVER['SCRIPT_FILENAME']);

By the way, @hendyanto's solution is also good. It is certainly robust against filename changes.

于 2013-09-05T06:59:02.067 回答
2

在页面上创建一个包含 header.php 的变量,稍后检查 header.php 中的变量以确定要执行的操作。

例子

在 home.php 中(将调用 header.php 的示例页面)

<?php
$page_code = "home";
include ("header.php");

/*Rest of your code*/

?>

在 header.php 中

<?php
switch ($page_code) {
case 'home':
    echo "include js and css here..";
    break;

case 'profile':
    echo "include js and css here..";
    break;

default:
    # code...
    break;
}
?>
于 2013-09-05T07:00:52.560 回答
0

我不知道它是否完美,但我在我的应用程序中使用它

任何页面.php

<?php
$js= "path/jstoinclude.js";
include "header.php";
?>

在 header.php 中

<?php
//your code
if(isset($js)){
echo "<script src='".$js."'></script>";
}
?>

通过这种方式,您可以将单独的 js、css 文件包含到不同的页面

于 2013-09-05T07:22:21.567 回答