Frage

I am struggling to figure out how to make my life easier with php by including php/html template files using the include_once ('asset/header.php') function for example. I am also wanting to use this for the css and js links on each web page. An example being:

<link href="css/font-awesome.min.css" rel="stylesheet">

What I want to achieve with each of these, is the ability to add a 'ROOT' or $baseURL for example before the link, so:

<link href="<?php $baseURL ?>/css/font-awesome.min.css" rel="stylesheet">

and

include_once ('$baseURL/asset/header.php')

I KNOW that the above is nowhere near right, I am not experienced in php programming, I just know it can make my life a lot easier when it comes to document paths. The problem I want to solve is simple: I don't want <img src="../../../../img/IMAGE.jpg> and include_once ('../../../assets/header.php') ^^ Examples here of course

I just want to put one generic code of php to print the root url before the image, css, html etc document path that it will include or import.

I have read a few instructional forums about this, but unfortunately, nothing I can figure out with my limited php experience. I would like to put the php root files in a config.php and restrict direct access if possible?

Also, I am currently using MAMP on mac. I have heard localhost may not work with some solutions, so any advice there will be great too!

War es hilfreich?

Lösung

Try using the $_SERVER superglobal

include_once $_SERVER['DOCUMENT_ROOT'].'/website/asset/header.php';

The realpath and dirname commands may also be of use.

Andere Tipps

First you need to declare your root variable like so:

$baseURL = "../.."; // or whatever it is

Then you can use the variable in the include like so:

include_once("{$baseURL}/asset/header.php"); // means include_once("../../asset/header.php");

Just make sure when you put the path inside of include_once, you use DOUBLE quotes and not single quotes, or else you can't incorporate variables like above.

Edit: One thing to remember, $baseURL must be in the scope of your include. As in, if it's a global and you're using it inside of a function, make sure you declare it as a global. More on scopes: http://php.net/manual/en/language.variables.scope.php

Why don't you try the $_SERVER['SERVER_NAME'] Function?

Example:

Echo("http://".$_SERVER['SERVER_NAME']."/asset/header.php")

You can try this:

require_once '../header.php';
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top