包括基于URL的javascript文件

i have an application in which i have created a header.php which is obviously common for all the pages in the app which i include on top of every other page. This header file contains the html head tags and DOCTYPE declaration etc and some common JS and CSS files needed for every page. But there are some specific files which i want to include depending on the page.

Now, how do i include a specific JS or CSS file based on the url from which the header.php is requested.

I tried to use $_SERVER['PHP_SELF'] at the top of header file to fetch the url but it did not work.

Please suggest with the best technique that should be used in this situation.

Sample Code

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>

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.

Create a variable on the page that will include header.php, later, check the variable inside the header.php to determine what to do.

Example

in home.php (sample page that will call header.php)

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

/*Rest of your code*/

?>

in 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;
}
?>

I don't know it's perfect or not, but i use it in my applications

anypage.php

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

in header.php

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

in this way you can include separate js, css files to different pages