How do I connect a single PHP script to multiple pages?


I want to display a "Last Published" date on my site’s articles using PHP. My site files are PHP pages.

Originally I had a piece of code in each article page, however I’ve now learned that is very bad design.

What code would I insert in my article pages to connect to a single, separate php script file, so that my "last modified" date will show up in my articles?

3 Responses to “How do I connect a single PHP script to multiple pages?”

  • Colanth:

    include() or require() the file with the code.

  • Freelance Web Programmer:

    You can use the php function filemtime($filename))

    $filename = ‘full path to the file.php’;

    // format it to look nice
    echo ‘Last Published: ‘ .date ("F d Y H:i:s.", filemtime($filename));

    To have this in its own separate include file is a bit of overkill. If you had multiple lines of logic then I would suggest writing a function. I have a common function file that I keep all functions in and then include it on each page.

    To write this as a function you could do this:

    // where $filename is the path and name of file you are using
    function _displayPubDate($filename){
    echo ‘Last Published: ‘ .date ("F d Y H:i:s.", filemtime($filename));

    }

    Then, in your code, you would output this where you want it to display

    <?= _displayPubDate("path/to/file.php"); ?>

  • Oh C:

    What I would do is this: make an array of all pages you want to be included.

    $pages = array(‘index.html’, ‘home.php’, ‘etc’, ‘etc’);

    then with that, you could use this code:

    function doIncludePages() {
    global $pages;
    foreach($pages as $page) {
    @require_once($page);
    }
    }

    and use that at the beginning of the file.

    Note: creating the array of pages could also help prevent being hacked, if you run a check.

Leave a Reply