0

I'm trying to create a php file which I want to include in various other php file and I am trying to add references to my CSS files but I'm having problems due to my directory structure. Off the root folder I have 3 folders, admin, includes and styles. The CSS files are located in styles folder and any files that I will include in pages are located in the includes folder. My problem is that I can't figure out how to ensure my CSS files are found, at present if I specify the location of the css files based on the root the files won't be found from the pages in the sub folders. I've tried solutions I found online including $_SERVER['SERVER_NAME'] and $_SERVER['DOCUMENT_ROOT'] without success and I have no idea what I'm doing wrong or what else to try. I'm completely new to PHP so any help would be greatly appreciated. Below is my code. Thanks

    <head>
<?php
    $server = 'http://'.$_SERVER['SERVER_NAME'];

?>
<!doctype html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <link rel="stylesheet" href="<?php echo $server . '/2025/styles/reset.css' ?>";
        <link rel="stylesheet" href="<?php echo $server . '/2025/styles/normalize.css' ?>";
        <link rel="stylesheet" href="<?php echo $server . '/2025/styles/characters.css' ?>";

</head>
0

2 Answers 2

1

Drop the $server variable and use a relative root URL. If the path to your file starts with a / that means to start at right after the domain and go under that path structure. For example:

Given this HTML element:

<link rel="/styles/reset.css">
  • On the domain example.com it refers to a file at http://example.com/styles/reset.css.
  • On the domain whatever.com it refers to a file at http://whatever.com/styles/reset.css.

The URL to the file is "relative" to the "root" of your URL.

Sign up to request clarification or add additional context in comments.

Comments

0

There are a couple of issues here.

The first is that using $_SERVER['SERVER_NAME'] means you are relying on your server configuration. It probably makes more sense to use $_SERVER['HTTP_HOST'] instead for this. A list of all $_SERVER options can be found here.

The second problem is that your HTML is not valid. You are not closing your link elements properly. You are using a semi colon incorrectly, they should look as below:

<link rel="stylesheet" href="<?php echo $server . '/2025/styles/reset.css' ?>" />
<link rel="stylesheet" href="<?php echo $server . '/2025/styles/normalize.css' ?>" />
<link rel="stylesheet" href="<?php echo $server . '/2025/styles/characters.css' ?>" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.