treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Php includes and CSS files.

  • So, I've figured out how to work php includes, but now I've encountered a problem when including css files.

    This is my directory:
    index.php
    header.php
    footer.php
    css/style.css
    work/index.php

    now the work/index.php i've figured out how to include the header which contains the css file links.

    The problem is, the css won't load from that work/index.php file.

    What do I need to add the to header.php file to get the css files to load no matter which directory a php file is calling it from?
  • To get it to work from any directory you could use the fully qualified URL
    When you include a file you always work with the location of the parent file
  • That needs to be done with HTML, not with php.


    <!DOCTYPE html>
    <html>
    <head>
    <title>This is a title</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    </head>
    <body>
    All of you content.
    </body>
  • When ./work/index.php includes ./header.php the browser reads the relative link of the CSS file (./css/style.css) and assumes the CSS file is relative to ./work/index.php and therefore looks for it at ./work/css/style.css.

    As @karlpcrowley said your link in header.php should have the full url so that it can be found from anywhere on your site.


    <link rel="stylesheet" href="http://me.mydesk.sit/css/style.css&quot; />



    or if you need php for changing hosts


    <link rel="stylesheet" href="http://<?php echo $_SERVER['SERVER_NAME']; ?>/css/style.css" />



  • Schmotty is spot on, but if you're going to be doing this a lot you are better off having a settings file and defining the absolute url
    This would make a difference on large sites
  • As I'm currently running on a local server, including a full url wouldn't work but once I finish development, I suppose I could go in and manually add in the full url.

    But how would I go about making a settings file to define the absolute URL?

    And as note, I know nothing about PHP, just how to work includes thats just because of wordpress development.

    Any help would be appreciated.

  • create a normal file to include
    then do something like this
    settings.php
    define('FULLURL','http://example.com/');

    your page
    <?php include "settings.php"; ?>
    <link rel="stylesheet" href="<?php echo FULLURL; ?>css/style.css" />

    Doing this is handy for other things like database credentials and some people even go as far as to specify maintenance mode in here as a Boolean value
  • Exactly what @karlpcrowley said. It's the best way to manage your URLs
  • make sure that include is at the very top of your index.php and any other php files that allow direct linking/access.