简体   繁体   中英

PHP - How to include php script without it running before including

In my file index.php I have included this text from another file.

<title>
  <?php

  $title = "";
  if (basename(__FILE__, ".php") == "index") {
    $title = "Home";
  } else {
    $title = ucfirst(basename(__FILE__, ".php"));
  }

  echo $title;
  ?>
</title>

And I guess you can see what i does, and if not, then it's supposed to set the title to the basename of the file. So say you have a file called downloads.php , then the title with this script would be Downloads . But I have this problem which I don't know how to get past. When I include the text via.

<head>
  include "filename.php";
</head>

And my problems is when I include the text, the 'script' runs before it includes. Say if the name of the file you included is filename.php and the main page where you have included the text is main.php , the header would be Filename and not Main . And the reason why I want to include the text, and not just paste directly into main.php is because it's much easier to edit if you have multiple files where you need the exact same code.

I hope you understand what I'm asking, and that you are able to help me.

Try $_SERVER['SCRIPT_NAME'] :

if (basename($_SERVER['SCRIPT_NAME'], ".php") == "index") {
    $title = "Home";
  } else {
    $title = ucfirst(basename($_SERVER['SCRIPT_NAME'], ".php"));
}

It looks like you're trying to set up a simple system for breaking your pages up into "subpages". Good idea. But rather than relying on the filename, why don't you set a variable? For example:

In page_title.php :

<?php
echo "<title>" . $title . "</title>";

In index.php :

<?php $title = "Home"; ?>
<head>
    <?php include "page_title.php"; ?>
</head>

In some_other_page.php :

<?php $title = "Some Other Page"; ?>
<head>
    <?php include "page_title.php"; ?>
</head>

And the same for any other pages you want...

In fact, you probably want to encapsulate the whole <head></head> section of your page.

Finally, rather than reinventing the wheel, you might want to look at some of the templating engines out there for PHP. I like Smarty , but there are others. These templating engines make it possible to write template files (including other template if necessary) and make it easy to simply pass variables to the template & render your HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM