开发者

PHP includes only for some pages

开发者 https://www.devze.com 2023-02-21 08:11 出处:网络
Is there a way to target PHP includes only for certain pages? I have to use PHP includes to call JavaScript and CSS files only for certain pages; pages not targeted for the include will not see either

Is there a way to target PHP includes only for certain pages? I have to use PHP includes to call JavaScript and CSS files only for certain pages; pages not targeted for the include will not see either the JavaScript or CSS otherwise they will break. Thanks

EDIT:

Thanks everyone. I've switched approaches. Instead of selectively using includes, I've decided to just 开发者_开发问答check the file name and link to JavaScript and CSS files to targeted pages. A colleague pointed to using $_SERVER['REQUEST_URI'] which would serve the name of the .php document and allow targeted delivery of JavaScript and CSS files. This is how I've set it up so far:

$files-array{file1.php, file2.php, file3.php}
if (array_search($_SERVER['REQUEST_URI'], $files-array) > 0) {
link to css files
link to js files
}


How is a page defined?

if($_GET['something'] == "somepage"){
include 'javascript.js';
}


You could do a bunch of things, however the main logic is:

if condition
  include file

So you could do something like:

if( $_SERVER["SCRIPT_NAME"] == "folder/script.php" ){

  include 'page.js';

}

or

if($_GET['variable'] == "correct"){
  // include
}

or

if($_POST['formvariable'] == "correct"){
  // include
}

and so on.


I'd recommend do your own library. So you don't mess the code up. You can make a simple catalog, something like this:

$pages_includes = array(
   'index' => array(
       'script1.js',
       'script2.js',
       'style1.css',
       'style2.css',
   ),
   'contact' => array(
       'script1.js',
       'style1.css',
       'style2.css',
   )
);

Then, in your "library" you could make something like this

function myImport($page_name){
    $includes = $pages_includes[$page_name];
    foreach(includes as $k=>$v){
       include_once($v);
    }
}

And, in your page you can do something like this:

myImport($_SERVER["SCRIPT_NAME"]);

Those are simple ways to organize your code and make it modular. If you have to change any imports you can do it in your Catalog ($pages_includes) and not in the code. Even you can read your catalog from a XML file.

A simple lesson of scalability and extensibility ;)


Can't you just use

if (condition) include 'something';

?

0

精彩评论

暂无评论...
验证码 换一张
取 消