I'm recently doing a website for a school project. In order to organize my work, I create a tree folder that keeps all the work organized. It is similar like this:
Back-Office
Pages
Home
home_test1.php
home_test2.php
home_test3.php
Login
Folder_Login
login.php
logout.php
Resources
CSS
style_home.css
style_navbar.css
style_footer.css
JS
script_home.css
script_navbar.css
Sections
navbar.php
footer.php
After all, with the require() method available in PHP, I want to call the "navbar.php" file to the "home_test1.php", "home_test2.php" and "home_test3.php", but the CSS style that is connected with the file "navbar.php" ("style_navbar.php"), doesn't display.
I've tried to change the path of the CSS style in the file "navbar.php" when I require() to the other file ("home_test1.php") and the CSS style shows up, but wont display in other file with a different path. How can I make this work dynamically? Sorry for long post and bad English grammar.
Thank you in advance.
You need to set your css and js files with absolute path instead of relative path
$dir = realpath($_SERVER["DOCUMENT_ROOT"]);
<link rel="stylesheet" href="<?php echo $dir.'/resources/css/style_home.css'; ?>" >
Without physically seeing you code it is quite hard to debug however there is an "obvious" answer that I'll suggest as a starting point.
The important thing to remember is that PHP and HTML are processed in completely different places. PHP executes on the server and should be used to build a full HTML "document" which it gives to the client/browser. The client/browser then reads the document provided and renders it according to HTML standards.
Calling require() will tell PHP to get the file and slot its contents directly where it was called and as it is a CSS file it will need to sit within the style tags. With a lot of modern browsers, if you use require on a file outside of the html tags, the content will be dumped at the top of the screen or simply ignored due to invalid syntax.
Alternatively if you would like to simply use tell the browser to include the CSS file, you could use the good old method of using <link rel="stylesheet" href="/path/to/file">. It's good to know when and when not to use PHP.
PS: You have .css files in your JS directory.
In PHP, there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:-
$_SERVER['DOCUMENT_ROOT']
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
<link rel="stylesheet" href="<?php echo $path.= '/Resources/CSS/style_navbar.css';?>" />
?>
I'm developing a website for my conclusion work at school. I'm using XAMPP v3.2.1. to localhost the site.
My site's folder's are configured just like this in htdocs folder:
ibnm
css
js
img
...
site
about
midia
...
includes.php
index.php (HOME PAGE)
My problem starts here: on index.php I'm including includes.php, that's a simple file with define() functions to the folders of my site so I can print the constant on the HTML tags of the site as URL (just like below)
//includes.php
<?php
define("css", "localhost/ibnm/css");
?>
//index.php
<?php
include_once("includes.php");
?>
<link href="<?= css; ?>/bootstrap.css" rel="stylesheet">
But when I do this, the CSS don't function. When I see an <a> tag with the previously defined URL on page it looks like
localhost/ibnm/site/localhost/ibnm/css
instead of
localhost/ibnm/css
It's confunsing 'cause if the <a> tag doesn't have any value (href="") it output localhost/ibnm/site/.
What can be wrong? XAMPP or coding?
Any url is not starts with http then browser will assume that its relative path so it will append to your current path, thats why your getting localhost/ibnm/site/localhost/ibnm/css.
And one small correction in your code, its not good idea to hard code server name in the code, better to get server name dynamically. So that you no need to change while deploying your site in real server.
//includes.php
<?php
define("css", $host='http://'.$_SERVER['SERVER_NAME'].'/ibnm/css');
?>
This is because the browser think localhost is a folder, and then do this ontop of the current path, to fix is just add http:// before the localhost
define("css", "http://localhost/ibnm/css");
Instead of using absolute path you can just add one slash before CSS path -
<link href="/<?= css; ?>/bootstrap.css" rel="stylesheet">
I have a form handler which is written in PHP and resides in a different directory than the html files. When the handler runs, it needs to include one of the html files. The html files have relative hrefs in them, which break because the page was served from the PHP directory, not the html directory.
For example, index.html contains
<link rel="stylesheet" type="text/css" href="css/site_global.css?4013920463"/>
These links are produced by Adobe Muse and expect that "css" is a subdirectory under the location of the html files and that the page was served from the html directory. Again, since I'm serving the page from the PHP directory, the relative links break.
Short of putting in absolute paths for the hrefs, is there any other technique I should consider? I really don't want to put in absolute paths because they will break for other reasons.
Ideally, I'd like to use some sort of method that allows me to set the "working path" in the browser - so that I can tell it to fetch hrefs from the right place.
Relative paths in a browser are computed based on the current page path (see here). If you are looking at http://foo.bar/one/page.html , the site_global.css path will be http://foo.bar/one/css/site_global.css .
If I understood your question, you can use the element to set a base URL for all the relative links in the page.
See here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
try $_SERVER['DOCUMENT_ROOT'], gives the path to your base directory with current working dir
or
try echo realpath(dirname(FILE));
UPDATE 1: to have a clear view of what is happening, you can download a snippet of the script from here.
I am working in a new website that has the same header, footer in all PHP pages.
In the header I am referencing to other common files in website that like .css, .js, functions, classes, db connection, and etc.
for instance, the default.css is in /common/stylesheets/
and my header.php and footer.php are in /common/html/ folder
so my header.php file is something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Header</title>
<link rel="stylesheet" href="common/stylesheets/default.css">
</head>
<body>
In my website index.php I included the header <?php include('common/html/header.php'); ?> and this is working fine... BUT the problems appear when I include the header in other php pages within other directories or sub directories e.g. /pages/admin/dashboard.php, everything messed up and that page no more linked to the default.css file.
So, what I am looking for is a method or logic where I reference to these common files and folders in every PHP page no matter its location; e.g. site root, a directory in the site root, or a sub-directory... etc...
here is an image of my website root
Your help is highly appreciated...
P.S. I've tried to use some superglobals variables such as $_SERVER[''] in config.inc.php file to define the paths, then I included that file in the header.php. BUT I couldn't figure out which one will dynamically keep referencing to those common folders and files no mater where the PHP page is.
UPDATE 1: to have a clear view of what is happening, you can download a snippet of the script from here.
It is usually a good idea to use fully qualified or absolute URLs to reference your assets:
<link rel="stylesheet" href="http://www.sitenamecom/some/path/to/common/stylesheets/default.css">
Since there are many places where you need the proper URL base to reach the different files, you could define a constant having the web root:
define('WEB_ROOT', 'http://www.sitename.com');
Then you could define other constants to have access to the different parts of the system:
define('WEB_ASSETS', WEB_ROOT . '/common');
So for the style sheet link in your header.php it would be:
<link rel="stylesheet" href="<?php echo WEB_ASSETS; ?>/stylesheets/default.css">
To include files the principle is the same only that in this case you don't work with URLs but with file system's paths. There's not really a dynamic way of solving this, it all goes down to absolute paths.
The problem here is that the tree structure in your local development environment might (and surely won't) match that of your server. So in the configuration file, which is located in your application's root you could define:
define('APP_ROOT', dirname(__FILE__));
Then lets use the admin/index.php file as example:
include '../../../config.inc.php';
include APP_ROOT . '/sitename/common/html/header.php';
The tricky part here is including the configuration. Since, until you do that the APP_ROOT won't be available, relative paths are needed to reach it, and it isn't possible to escape this one; unless you can fully trust the preferred absolute form:
include '/some/path/to/config.inc.php';
Having that leading slash, as I said before, will be a problem if the application is tested in different environments because it is rarely the case that some/path/to is always the same.
This is the usual issue with structures that aren't using index.php for centralization. Maybe you can try adding another include that defines your directories as pseudo-constant and prepending them to your asset urls.
Or you can parse the request url on how deep it is and automatically prepend the needed ../ levels to your assets urls. I've done this for one of my past projects.
I got to warn you though, it's better to solve the root of the issue (lack of centralization) than adding workarounds. It will surely come back to haunt you sooner than you think.
$_SERVER['DOCUMENT_ROOT'] is likely what you are looking for.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/sitename/common/html/header.php");
This should work from any directory. If you want it to be a little more dynamic than typing out "sitename", you can do this:
<?php
$sitename = explode("/", $_SERVER['REQUEST_URI']);
require_once($_SERVER['DOCUMENT_ROOT'] . "/" . $sitename[1] . "/common/html/header.php");
You need to Change your <link rel="stylesheet" href="common/stylesheets/default.css"> to <link rel="stylesheet" href="../../common/stylesheets/default.css">
here is a simple modification in php.ini to include footer.php and header.php for each script
auto_append_file=ABSOLUTE_PATH/footer.php
auto_prepend_file=ABSOLUTE_PATH/header.php
restart your Apache if you are running under easyPhp, xampp,....
Warning : This configuration will be applied in all projects that are executed with the modified PHP
Try <link rel="stylesheet" href="/common/stylesheets/default.css">
Note the leading slash... This directs server to the document root.
I tried it and it works.
My tree:
/var/www/html/
subdir/
body.php
layout/
header.php
footer.php
css/
style.css
header.php
<html>
<head>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<p>Header.</p>
<hr>
body.php
<?php
include($_SERVER['DOCUMENT_ROOT'].'/layout/header.php');
echo "Body.<br>";
include($_SERVER['DOCUMENT_ROOT'].'/layout/footer.php');
?>
footer.php
</body>
</html>
style.css
body {
color: red;
}
Viewing http://localhost/subdir/body.php in the browser, I get the expected result: "Header" and "Body" are colored red.
I would store the document root of your website in some define:
define('DOCROOT', $_SERVER['DOCUMENT_ROOT']);
Do this in a PHP file that you include everywhere, preferably in some bootstrap PHP file.
Then you need to prepend your paths with this in your include lines:
<?php include(DOCROOT . "/common/html/header.php"); ?>
Have you also looked at include_once?
Have you tried PHP's set_include_path ?
You can add numerous paths in one set_include_path separating them with a ' :'.
set_include_path('/home/mysite/includes1:/home/mysite/includes2').
PHP.net -> set_include_path
Even without moving to a full front controller (and MVC) setup (which would be good), you are going to save yourself a lot of headaches if you introduce a simple bootstrap-like file.
It's not going to be perfect with your current setup, as your files are including different parts of your system (ie header.php) in various places and sub folders.
Having header load the first output things - i.e. doctype, head and head links etc - is fine in your basic structure, but you have now run into constraints which you cannot work around without making your header.php messy, or including numerous other files before header.php.
In a more solid framework design, the html and doctype outputs are after a lot of other things have been initiated and loaded, to allow control over said html and doctype.
But to help in your case, just load the bootstrap before anything else is loaded/included.
Bootstrap
The bootstrap will load shared resources, and common used data and paths (etc) throughout your application.
You can then add anything else in the bootstrap in the future, if you find a scenario.
A simple example of something in your bootstrap:
bootstrap.php (MUST reside in your root web folder for following constant to work)
// Define root folder
define ('FOLDER_ROOT', __DIR__);
Then throughout your app you can reference that constant (FOLDER_ROOT) to determine the root folder, and work through subfolders as required.
So, using your current setup:
index.php (I presume is in root folder)
include('bootstrap.php');
include(FOLDER_ROOT.'/common/html/header.php');
// Everything else
So then in your bootstrap you can set other things, such as define the default doctype or character encoding, setup error management.
Although you would usually set things like doctype after bootstrap, in a class, the router, some controller, or even a template.
But as you are using common file includes rather than using a more conventional framework design pattern, this way will at least save you some headaches now, and possibly further down the line.
So again in the bootstrap.php:
// Define root folder
define ('FOLDER_ROOT', __DIR__);
// Define CSS folder using root folder constant above
define ('FOLDER_CSS', FOLDER_ROOT.'/common/stylesheets/');
Then in header.php:
echo '<link rel="stylesheet" type="text/css" href="'.FOLDER_CSS.'default.css">';
Sub Folders (ie /admin)
Now in sub folders, such as /pages/admin/dashboard.php etc, you don't have access to these constants, because you are loading your header files and other template like things all separately "across your application".
So it becomes a battle to set your root folder, plus you are now managing it all twice!
You could try loading the root bootstrap file within your admin folder.
So in dashboard.php, something like:
include('/bootstrap.php');
// OR (more likely)
include('../../bootstrap.php');
But this is becoming messy, calling bootstrap in different places, having to call it differently too.
It's not ideal, but it is do-able, in that if you get the bootstrap loaded within your admin area, then you have the root path setup in admin area and so managing other files from your admin files should be easier.
You could try using a new admin specific bootstrap file, eg in /pages/admin/, have adminBootstrap.php.
But then you're setting two different constants for root, and likely more constants to get to your common and css files and folders. It's easy setting your web root path in a file that is in the web root path, and can be tricky (sometimes) setting web root path from another folder.
Stylesheets
You mentioned that using /common/stylesheets/defaults.css (with a preceding slash) doesn't work and causes the source code to show localhost/common/stylesheets/defaults.css.
This would possibly indicate you need to configure your DocumentRoot.
On Linux it's in /etc/apache2/sites-available/, then either the default file, or if you configured your own virtual sites then go into each one.
What is your DocumentRoot set as?
Although if you get the bootstrap working within the admin area this problem might go away, using the constant FOLDER_CSS.
Folder Structure
I also think you should tidy up your folders, as you seem to have separated things into illogical folder names (perhaps logical to you, but will it be when you learn more and come back to it in a year, or another dev tries to use it?).
E.G. I would not know what on earth the folder html is going to contain, as HTML is a protocol, and ultimately your application will serve HTML.
Have a little read into MVC. Don't go into depth as it's a lot of reading/learning, but if you grasp the basics, you can then tidy up your own structure to create your own logical separation of presentation from business a little more logically than it is now.
Front Controller
If instead of using include files, you had a framework, which loads bootstrap and application wide configs, error management, other stuff, then when you come to load your HTML (your header, footer etc), they will have all this application (root folder constants etc) pre-loaded regardless of which sub folder you are trying to load web pages from.
However as you are doing it, you are instead including these things manually whenever you need them in different files, in sub folders.
While you are introducing a small presence of DRY (Don't Repeat Yourself) by having the doctype, head, etc in include files and re-using them, you are still having to repeat yourself with those include files as you re-use them wherever you need them.
Also, what if you wanted to re-style admin differently to the main site? You'd have to include a different header file or a different stylesheet, or just put all code in the same stylesheet.
I'm waffling, but hopefully I'm being clear, and you can see why using header includes is only a small step in the right direction and for small sites. I'm sure you progressed naturally to using those include files from typing out the head/doctype etc in every file.
However now you are trying to break out into other directions, as with your admin area, you can see the constraints and including those same files is becoming harder to manage as your entire application grows.
So if you had a front controller type setup, within your dashboard.php you would have been able to simply used the constants set in the root bootstrap file, and any other sub folder which would be accessed after the core application is loaded.
EG (if using front controller like pattern)
dashboard.php:
include(FOLDER_ROOT.'/common/html/header.php');
I know I've bashed on about front controller already, but a few years back I was at the stage you are now, and moved from having all my files including the header.php, then the page content, then including footer.php, etc, and I instead started using a front controller.
It's really sooo much better!
It is a fair learning curve (with learning curves in all sorts of directions and methods, requirements, etc) and as such will leave it up to you if you want to go further into that.
I now have my own basic MVC front controller system, which I just simply plonk a new file for a new website page into the view/pages folder, and the page can be used immediately in the browser (the system does everything else).
In my root directory I have a bunch of single pages and then the folder "blog" and "assets." For the pages I have a header.php/nav.php/footer.php to call for various css and js.
for example: within the header.php:
<link href="http://beta.rfahaiti.org/assets/css/bootstrap.css" rel="stylesheet">
Then, in the pages I call for: <?php include 'assets/header.php'; ?>
However, this does not seem to be working for any pages within the blog folder -- such as the index.php file in /blog/news/. I assume it's a relative vs absolute link issue but I'm not sure how to fix. Question: what does the php include call need to be for to call for the header.php file?
Thanks!
Try:
<?php include '../assets/header.php'; ?>
or
<?php include '../../assets/header.php'; ?>
depending on your folder structure.
Include paths are relative, try:
<?php include '../assets/header.php'; ?>
You will find the same with HTML document referring to resources e.g CSS.
It is a relative link issue, as you say. For pages two levels deep in /blog/news, you need to go two levels back:
../../assets/header.php
Edit thanks to Juan Sosa for pointing out that what follows is completely wrong.
Alternatively, you could write this:
/assets/header.php
The second approach is cleaner in one sense; however, beware it assumes that your site will always be located at the root of the domain (ie, if it ever got moved to http://beta.rfahaiti.org/theapplication/ or something, then all those type of links would break).