PHP Include Paths - php

I'm new to PHP and I'm having a problem when trying to link my CSS files using include.
Basically I need my files to link back to a certain directory no matter how far down the file is. I have tried using
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/sysprogs/required/header.html';
?>
But header.html contains the links to my css files so the directory it ends up looking for the css files in is
http://localhost/SysProgs/software/CSS/style.css
instead of where I want it to go to which is
http://localhost/SysProgs/required/CSS/style.css
I hope that made sense and I hope you can help me
Thankyou for all your help everyone!

I would definitely not use <base>. I've run into many problems with this before. If you use <base>, ALL of your links will become relative to that base value.
Instead, I would recommend setting PHP constants for common directories. For example:
PHP Code:
<?php
define('CSS_DIR', '/SysProgs/required/CSS/');
?>
HTML Code:
<link href="<?php echo CSS_DIR ?>style.css" rel="stylesheet" type="text/css" />

One Idea
Use the full URL in header.html. This will be unambiguous and robust.
<head>
<link href="/FULL_BASE_URL/style/style.css" rel="stylesheet" type="text/css" />
</head>
Another Idea
Use the <base> header tag. This allows you to specify a base URL for links, including CSS, and may require the least work in the short term (see note below).
<head>
<base href="FULL_BASE_URL" />
<link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
More at w3schools
Note: As is noted in the comments below base may ultimately cause more confusion than it is worth.

I like to define both an absolute path and a webroot in a central place in your application:
<?php
define("APP_WEBROOT", "/myapp");
define("APP_ROOTDIR", "/home/www/example.com/htdocs/myapp");
?>
you can then "absolutize" the correct links like so:
<?php echo APP_WEBROOT; ?>/software/CSS/style.css
I prefer this
over <base> because that tag creates confusion and makes code harder to maintain in the long run
over using absolute paths /software/CSS/style.css because those make you unable to install your application in a subdirectory of your choice: You will always be bound to the root directory.

I run into this problem a lot when designing sites. When I have custom CMS, I use the following:
$basedir = "root_directory/";
$basedirPHP = $_SERVER['DOCUMENT_ROOT'].$basedir;
$basedirHTML = "http://".$_SERVER['SERVER_NAME'].$basedir;
I define $basedir so I can move the site to different subdirectories in the server without any effort. The $basedirPHP and $basedirHTML are so I can call on files either with php, or like you mentioned, when linking CSS, JS, etc.
If you're on wordpress, just use the good ol' bloginfo('template_directory'); to do the same in template files.

The first thing for you to understand, is your question has nothing PHP related. It is as simple as just filenames in your HTML questuon. Without PHP it will remain the same. Just use absolute path to your CSS file
And another thing to think of: consider to accept some questions.

Related

PHP Require method doesn't show any CSS style

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';?>" />
?>

Relative URL issue

I will have multiple folders/modules to access common files. But accessing them seems to be big deal for me!
I did gone through this link to understand the relative positioning and managed to solve some . But not all. Reference: Relative URL's/paths in php
My folder structure is as below:
Website runs on root folder:
/(index|ajax).php
and then the subfolders:
/css/style.css
/img/*.(jpg|png|gif)
/inc/(header|footer).php
/js/*.js
/registration/(ajax|getsubjects|response|success).php
Now, this is how I included files in the index.php page(this displays correctly, meaning, style,css,js,config all accessible)
<?php
include('inc/header.php');
?>
content here
<?php
include('inc/footer.php');
?>
This index page will have to fetch getsubjects.php, response.php and then finally land in success.php.
The success.php need some styling whereas the previous two were only for processing.
So now in the success.php I access header and footer as below:
include('../inc/header.php');
include('../inc/footer.php');
But this doesn't apply any styling!
inside header.php and footer I include files like this:
<link rel="stylesheet" href="./css/style.css">
<script src="./js/script.js"></script>
How should I include the files here please?
./css/style.css means from current directory and would achieve the same result as css/style.css. The easiest answer is to determine what the base path of your application is and use that. For instance, if your application is running as http://myapp.com, then you could set all your front-end paths to /css/style.css. If your app runs in a subdirectory, such as http://example.com/myapp, then your paths would be /myapp/css/style.css.
This does not apply the same on the PHP side. For them, you should really use document-relative paths. Having a PHP file that you include in multiple places in your app, the contents of which having something like include('../myDoc.php');, can lead to complications as the path isn't based on the included document's path, but rather the including. So using document-relative paths, you get around this include(__DIR__ . '/../myDoc.php');. Just something to consider if your app grows.
Your PHP-includes seem to be correct. But in your HTML you need to change the linking to the CSS and JS Files (maybe even to your images).
You could use absolute paths:
<link rel="stylesheet" href="/css/style.css">
<script src="/js/script.js"></script>
the leading dot makes your paths relative to the HTML-Document, so if they are linked from a document in a subfolder, they point to a wrong location.
Including files with
<?php
include("page1.php")
?>
put the code (or content) from page1 into the caller page.
So you may have to detect from where your pages are called, or try absolute links (beginning by /)
I hope I answer you question correctly.

Yii including CSS and JS files

I've been reading on this quite some time...and i'm puzzled -
Can you help on what is the difference between:
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/some-file.css');
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/some-file.css
Is it a performance issue, or just different syntax?
Thanks,
Danny
registerCssFile always registers the file between the <head> tags, even if you call it somewhere in a view.
This is helpful if you care about HTML validation (a <link> in <body> is invalid), but still want to include a CSS file in a view.
registerCssFile actually aids performance, because the CSS is registered only when you want it (and need it).
The way you are using it, it is identical. To verify this, check the source of the page (in your browser) and check the statement that Yii::app()->clientScript->registerCssFile creates.
However, clientScript lets you control the position of the script in the HTML file. Check out: http://www.yiiframework.com/doc/api/1.1/CClientScript#registerScriptFile-detail and look for POS_HEAD, POS_BEGIN, POS_END.
What is probably more important is this: In the MVC philosophy, you want to have everything related to HTML-output in your view-file. Yii::app()->clientScript lets you add CSS and JS files from within your view files. And that is where you want it.

File Structure for a PHP Project

My file structure:
/holiday/admin/list.php
/holiday/includes/functions.php # common functions
/holiday/index.php
# / is the document root
# /holiday/ is a "self-contained" sub-directory
# There are other "self-contained" sub-directories e.g. /promotion/, /international/
In functions.php I have a common function to generate the <head> part of an HTML; also, a function to return an absolute path from the document root. Note my attempt to calculate /holiday/includes/.
<? function get_path() {
// Technically, this returns dirname(__FILE__) - $_SERVER['DOCUMENT_ROOT']
return str_replace($_SERVER['DOCUMENT_ROOT'], "", dirname(__FILE__));
} ?>
<? function open_page($head = "", $body_id = "") { ?>
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="<? echo get_path() . "/../css/savvyextras.css"; ?>" />
<script type="text/javascript" src="<? echo get_path() . "/../scripts/modernizr.js"; ?>"></script>
...
<? } ?>
functions.php is included this way:
// From list.php
require_once('../includes/functions.php');
open_page(...);
// From index.php
require_once('./includes/functions.php');
open_page(...);
I feel like there must be a more straightforward approach to accomplish the same thing here. Any built-in PHP function for my get_path()? Maybe I should approach my problem differently?
Note:
Some folks suggested using a framework (which is a good thing). But, to help me (and others) understand this whole include-file thing, other non-framework explanations?
Related Discussions:
Absolute Path for Deployment in a Non-Root Location
Including files by relative path
#Siku-Siku.Com, auto-loading classes with __autoload() won't really help your main problem. Besides, you'll only be able to get the most out of __autoload() if you move to a mainly object-oriented design, which will bring its own challenges.
Currently, the most sensible thing to do would be as #hafichuk suggests. Make one main includes file, say my_funcs.inc.php, and include it at the top of every other page you have. The advantage is that by giving special .inc extensions to your include files, you can distinguish them more easily. Plus, you can use that to block these files in Apache for just an added bit of security.
If I could also mention:
1) I think short tags are risky. They encourage bad coding practices and leave the door wide open for porting nightmares. And they encourage bad coding practices.
2) Since require is a statement, not a function, it should be used like:
require 'my_file.inc.php';
With the type of layout that you currently have, your best bet is to have a single includes.php file which holds all of your require_once calls, then use require_once('../includes.php') (or equivalent location) at the top of each of your entry scripts. It's a pain to setup and maintain, but at least it's all in one place.
If you plan on moving towards using objects instead of functions, then I'd take a look at using __autoload().
After experimenting more with this and gathering other inputs, I find using constant will do the trick:
# functions.php
define('PREFIX', '/holiday');
<? function open_page($head = "", $body_id = "") { ?>
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="<?php echo PREFIX; ?>/css/savvyextras.css"; ?>" />
<script type="text/javascript" src="<?php echo PREFIX; ?>/scripts/modernizr.js"; ?>"></script>
...
<? } ?>
So, if you need to move /holiday/ to a different sub-directory e.g. /vacation/, you'd simply need to change one constant i.e. PREFIX.

Parent directories and PHP

I really hope there's a simple solution to this.
<?php include("header.php"); ?>
Let's say I have a php header in my root folder simply titled header.php. In that header there is a link back to the home page, main.php, and main.php is also located on the root. No problem so far. Here's what header.php looks like. Simple stuff, right?
<link href="style.css" rel="stylesheet" type="text/css" />
<div id="headerwrap">
<div id="linkbox">
<img src="images/mainlogo.png" />
</div><!-- End linkbox -->
</div>
However, let's say I have other pages in subdirectories. Subpage.php is located in a child directory of the root, and so it has to look back to the root to get the included header.php.
<?php include("../header.php"); ?>
That wouldn't be a big deal, except that header.php links back to main.php and also style sheets, none of which are in *subpage.php's directory, thus causing an error when someone on Subpage tries to get back to Main via the link in the header.
I'm just hoping there's a simple way to make this work, and that I don't have to copy and redirect all includes into every subdirectory. Also, there are too many pages to really reasonably include them all on the root. Sorry if this answer is posted elsewhere; I've looked and just have no real idea what I'm looking for. Thanks for your help. Hope all that makes sense.
You could just hard code main.php's path within header.php:
<img src="http://website.com/images/mainlogo.png" />
As opposed to a php prob this seems to be an html prob..
Your links should be relative links with a preceding / i.e.
Text
instead of
Text
how about using absolute links. header.php should also reference main.php absolutely, then there should be no troubles:
<?php include($_SERVER['DOCUMENT_ROOT'].'/header.php"); ?>
You can use the base html tag:
<base href="http://yoursite.com/" />
This way you can use that url as the base for all your links/stylesheets/images and you don't need to worry if they're in a subdirectory.
the best thing to do is to get in the habit of using
$_SERVER['DOCUMENT_ROOT']
that way you have no confusion as to what directory you're in, etc.
so including your header for example would be as simple as :
include $_SERVER['DOCUMENT_ROOT'] . "/header.php";

Categories