Arnold Porche Villaluz
Arnold Porche Villaluz

Reputation: 213

How to preserve path structure with PHP include?

I have a toolbarMenu.php that uses css in a css directory ("css") from the root folder.

All of my other PHP forms are in a root folder, and planned to re-organize all my PHP form to be move to a new folder called "forms" exluding toolbarMenu.php

After I move my PHP form to sub-directory, I can call this toolbarMenu.php by using include ex:

<?php include("../toolbar-top.php"); ?>

However, the CSS path broke because it's trying to look for the css folder inside the forms folder. I don't want to change the css path from my toolbarMenu.php to "../css/file.css" because I'm also using this php page with the website's root pages.

Is there a way to preserve the toolbarMenu.php's css path when it's being called from a PHP form from another sub-directory?

From Root folder:

Toolbar Menu path: "toolbarMenu.php"

CSS path: "css/cssFile.css"

PHP form calling the ToolbarMenu: "forms/form.php"

I hope I made my question clear :)

Thanks!

Upvotes: 0

Views: 3198

Answers (3)

Phil
Phil

Reputation: 164811

You can either use an absolute path, eg

<link rel="stylesheet" type="text/css" href="/mySite/css/file.css">

or, if you want to keep it portable, set a dynamic <base> for relative paths. This way you can move your entire app to a sub-directory without breaking reference links, eg

<!-- in HEAD -->
<base href="http://localhost/mySite/">
<link rel="stylesheet" type="text/css" href="css/file.css">

Upvotes: 4

Tarek Fadel
Tarek Fadel

Reputation: 1959

You have multiple options to get the desired result:

  1. You can define a prefix variable/constant at the top of every page which you then use in all your includes/urls/etc.
  2. You can also use the <base> tag in your header pointing to the absolute URL to ../ so something like http://ys.cc/proj/ if your forms directory is http://ys.cc/proj/forms

Upvotes: 1

You can write your css file selector from:

css/file.css

to

/css/file.css

This will work in all folders.

Upvotes: 0

Related Questions