How to use relative paths for included files like .css

I have a file header.phpthat contains a link to a file .css.

When I "include" header.phpin another php file in another folder, .csshref is header.phpnot suitable for this for a new php file.

How should I declare hrefin my file .cssto include in it header.phpwhich will be correct for any folder where the php file is located?

+5
source share
8 answers

This is the reason why many large applications will try to set the constant / variable of the root URI during installation.

/css/style.css , /, , (/appName/css/style.css)

URI "root" script / , .

define( 'SCRIPT_ROOT', 'http://localhost/yourApplication' );
// ...
echo '<link rel="stylesheet" type="text/css" href="'.SCRIPT_ROOT.'/css/style.css">';
+15

, .

base href

<head>
<base href="http://www.mysite.com/" />
</head>

, hrefs . <link rel='stylesheet' href='css/mycss.css' /> mycss.css, http://www.mysite.com/pages/2012/public/secret_folder/myownphpfile.php

aboslute, , .

<link rel='stylesheet' href='http://www.mysite.com/css/mycss.css' />

@Discomatt, PHP - . ; PHP. , ^^

define('CSSDIR', 'http://www.mysite.com/css/);
<link rel='stylesheet' href='<?= CSSDIR ?>mycss.css' />
+8

, href, , . (, http://myproject.example.org/, http://example.org/myprojecttest/). , CSS- :

<link href="/css/style.css" />

, :

, header.php, $ ROOT, . :

$ROOT = './';

$ROOT = '../';

$ROOT = '../../';

header.php :

<link href="<?php echo $ROOT; ?>css/style.css" />

header.php, .

(/path/header.php)

<html><body>
<head>
    <link href="<?php echo $ROOT; ?>css/style.css" />
[...]

1 (/path/index.php):

<?php
$ROOT = './';
include 'header.php';
?>    

1 (/path/admin/index.php):

<?php
$ROOT = '../';
include '../header.php';
?>    

3 (/path/admin/test/magic.php):

<?php
$ROOT = '../../';
include '../../header.php';
?>    
+5

css, :

<link href="http://site.com/css/style.css" />

+1

:

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

/ : " ". .

0

Tom answer base url PHP define ( ).

- PHP:

define("HOST_BASE", "http://example.com/");

:

<base href="<?php echo HOST_BASE ?>">

, , , , . MDN.

0

URL- CSS JavaScript.

, .

define ('host_address','http://localhost:85/grc/');
define('css', host_address.'styles/');

URL host_address CSS , .

<link rel="stylesheet" href='.css.'custom.css>
0

css js :
fooobar.com/questions/14900909/...

With this trick, you simply call c1CssImport (), where you want to include CSS files based on the relative URL:

c1CssImport('./ui.css');
0
source

All Articles