Askingtoprogrammers
Askingtoprogrammers

Reputation: 3

How to get css file from any file using php?

Here is what I want to state I have this structure-

enter image description here

Now considering the directory I want to add the CSS file to all the files if I am using the project-1 > sub-project > subfile.php
then I should be using <link rel="stylesheet" href="../../asset/css/style.css" />

Again if I use the project-1 > file.php
then I should be using <link rel="stylesheet" href="../asset/css/style.css" />

Now even if I use index.php
then it should be like <link rel="stylesheet" href="asset/css/style.css" />

In short, I want it to access CSS file from any file dynamically. It's a type of autoloading whenever included.

I have tried something but it failed because it's not dynamic

$search = glob("asset/css/style.css");

foreach ($search as $ser) {
    $ser = $ser;
}

if(strpos($ser,"asset") !== false){
    echo "<link type='text/css' rel='stylesheet' href='asset/css/style.css'>";
}else  {
    echo "<link type='text/css' rel='stylesheet' href='../asset/css/style.css'>";
}

But the problem is it is not dynamic. Please provide a solid solution. Thanks a lot in advance.

Upvotes: 0

Views: 146

Answers (1)

Serghei Leonenco
Serghei Leonenco

Reputation: 3507

I'm assuming you have domain name like:

domain.local

And your init style url looks like that:

href="asset/css/style.css"

Then you trying to access your project located under proj1 directory:

domain.local/proj1/index.php

using same styles method the url will look like this:

domain.local/proj1/asset/css/style.css

And they are no longer applied

Solution:

You need to use relative approach. Try this in your link:

<link rel="stylesheet" href="/asset/css/style.css" />

This will helps you no mater how many directories are, always grab styles using root as initial point. Here are relative question: Why the CSS style is not applied in webpages within subdirectories?

Upvotes: 1

Related Questions