Absolute paths within includes with localhost - php

all.
My question is in regards to a problem I'm encountering when trying to add a universal php template for my DOCTYPE section. My DOCTYPE include (aptly entitled doctype.php) lies within the /template directory, and also includes calls pointing to my CSS and JS files that I want to be accessible to all pages.
So the problem is encountered when I try to write the absolute path to these files (the CSS and JS files). Currently, I am trying:
<script type="text/javascript" src="<?php echo $_SERVER['DOCUMENT_ROOT'] . '/file/extension/to/javascript/file.js'; ?>"></script>
and
<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['DOCUMENT_ROOT'] . 'file/extension/to/css/file.css'; ?>"
I am running the application through WAMP on my localhost.
Taking a look a look at the source code, it appears as though the links are pointing to the appropriate files (c:/wamp/www/examplesite/path/to/file/file.ext), and all should be well. BUT it is not...
The JavaScript is not accessible and the Stylesheet is not functioning. I'm at a loss for what to do.
I've also tried:
-writing the absolute path without the use of PHP
-creating PHP variables to hold the document root and then concatenating the appropriate directory path to access the files.
Any suggestions? And how will this change when I upload the directory structure to my online server vs. my current localhost?

You might want to try $_SERVER['HTTP_REFERER'] instead. It gives you the path you are looking for.
On my local machine, which uses WAMP, I used <?php print_r($_SERVER); ?> to see what values it gives.
Also, there may be some typos in the snippets. For example, you don't need the leading / in the first example you gave.
For example:
<script type="text/javascript" src="<?php echo $_SERVER['HTTP_REFERER'] . 'file/extension/to/javascript/file.js'; ?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo $_SERVER['HTTP_REFERER'] . 'file/extension/to/css/file.css'; ?>"></link>
Or since HTTP_REFERER can't be trusted in some case, you may want to create a function that builds the base part of the absolute path.
<?php
function getAddress() {
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
$filenamepattern = '/'.basename(__FILE__).'/';
return $protocol.'://'.$_SERVER['HTTP_HOST'].preg_replace($filenamepattern,"",$_SERVER['REQUEST_URI']);
}
?>
Then call it like so:
<script type="text/javascript" src="<?php echo getAddress() . 'file/extension/to/javascript/file.js'; ?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo getAddress() . 'file/extension/to/css/file.css'; ?>"></link>

You're pointing to files on your local machine using the file path (ex: C:\some\path\to\file) when you should be using a URL (ex: http://localhost/some/path/to/file). The HTML is parsed by the client's browser so when it attempts to access a path that isn't a URL it can't.
Instead of using $_SERVER['DOCUMENT_ROOT'] you can either use absolute URLs such as
<script type="text/javascript" src="/path/to/my/file.js"></script>
where the "/path" folder is your base web directory, or you can use relative URLs based on whatever the current directory the file is in to which you're including the doctype.php file. I'd recommend not doing the latter as it's a pain in the butt to keep track of.
If you use relative URLs you should have no problems when moving your code to a new host, provided the directory structure remains the same.

Of course any kind of resource (JS, CSS, Images, etc.) has to be accessed via http(s) request and therefore it is impossible to directly access them with an absolute path. Think of the security implications of such an approach. So you always have to use web paths relative to your web root directory.
For example:
<script type="text/javascript" src="http://localhost/myproject/media/ja/file.js"></script>

You're going about the wrong way of including files in your page, you should be using HTTP URLS instead:
<script type="text/javascript" src="/file/extension/to/javascript/file.js"></script>
Or, if you prefer to use a variable with the host name:
<script type="text/javascript" src="http://<?php echo $_SERVER['HTTP_HOST']; ?>/file/extension/to/javascript/file.js"></script>

Related

CodeIgniter relative path or base URL function?

All these days I thought that CodeIgniter did not allow direct access to file(s) in the application (I mean the application itself and not the application folder).
So, if I have the following structure under the folder, www:
ROOT
|____APPLICATION
|___________JS/mine.js
|___________VIEWS/my_view.php
And if I want to include mine.js in my_view.php, I would need to refer the JS file using the base_url() function as follows:
<script type="text/javascript" src="<?php echo base_url();?>js/mine.js"></script>
Looks like I was wrong, I can refer to it relatively as well. Like:
<script type="text/javascript" src="../js/mine.js"></script>
Any thoughts/opinions?
Which one is a good practice? And why?
It's always a smart idea to use base_url() so if your URL changes, all your links don't break.
base_url() is going to return the full TLD, plus any folders your site is in.
Best practice is to keep your assets out of the application, or any other system folders. Most CodeIgniter sites will structure their assets as follows:
ROOT
|____APPLICATION
|____ASSETS
| |________ CSS
| |________ JS
| |________ IMG
|____SYSTEM
And then referenced like so:
<script type="text/javascript" src="<?php echo base_url('assets/js/mine.js')"></script>
It is always a good idea while using MVC to keep all assets folders (css, js and images) in root directory rather than keeping inside application or any other folder and accessing them using base_url.
<script type="text/javascript" src="<?php echo base_url();?>js/mine.js"></script>
So I think above line you mentioned is the proper way.

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.

PHP global path setting

I have this setting.
root dir|
index.php
config.php
file.php |
|
|scripts|a.js
|
|account
|index.php
| |
|member |index.php
Now, I've included index.php of member dir into index.php of account dir. Also , the account index.php includes the config.php which contains,
define( 'PATH', (__DIR__) );
Now , for all includes in account index.php I use,
require_once( PATH . '\file.php' );
and is working properly. But when I try to add the path for script src such as,
<script type="text/javascript" src="<?php '.PATH.'scripts/livevalidation.js ?>"></script>
I get an error, so how can i include the a.js in scripts folder into index.php of account using the globally defined path.
Thanks.
The PHP "__DIR__" and "__FILE__" are absolute to the server. You shouldn't need to use either for your script.
<script src="/scripts/livevalidation.js"></script>
Also, your PHP looks like it has some syntax errors, this would be correct (although still wouldn't work:
<script src="<?php echo PATH.'/scripts/livevalidation.js'; ?>"></script>
You're missing a print or echo statement in the PHP statement in your script tag. You're also placing the concatination periods in the wrong place. On top of that, however, the JavaScript you're trying to include doesn't need to be in the PHP statement.
All that said, the final line should read like the following:
<script type="text/javascript" src="<?php echo PATH ?>scripts/livevalidation.js"></script>
On top of that, however, I don't think the above will work as you expect. __DIR__ outputs a server-side filesystem path, which wouldn't make sense when importing JavaScript over HTTP. I'd recommend something more along the lines of the following:
<?php define('URL_ROOT', '/'); ?>
<script type="text/javascript" src="<?php echo URL_ROOT ?>scripts/livevalidation.js"></script>
In the above example URL_ROOT would point an absolute URL under which your static media (CSS, JavaScript, and so on) is served.

is it worth it to use base_url() for every clientside inclusion?

I use CodeIgniter and i love it, but i don't know whether it's really worth it to do like this:
<link rel="stylesheet" href="<?php echo base_url(); ?>css/main.css" />
<script src="<?php echo base_url(); ?>js/jquery.js"></script>
<script src="<?php echo base_url(); ?>js/functions.js"></script>
...
<img src="<?php echo base_url(); ?>images/dolphin.png" />
Rather than just:
<link rel="stylesheet" href="/css/main.css" />
<script src="/js/jquery.js"></script>
<script src="/js/functions.js"></script>
...
<img src="/images/dolphin.png" />
The first method adds a lot of weight to the page but it's reliable when you decide to use the same app in a subfolder and such.
Which one should i go with?
If you think you might need to move the app to other subfolders (and not other sub domains), it probably is worth using <?php echo base_url(); ?>, however if you can assume that the app will always be installed on it's own domain or sub domain definitely do away with the function call, it adds unnecessary clutter and sends more to the users browser.
It's down to what you think your application will need to do.
In my opinion you should always use base_url() for defining your path because like that you will make sure that your path will always be the right one. If you think that echo function is too dirty, you can always use Template engines like Code igniter built in template parser class or some external like Smarty.
Just thought I'd add some things that has been relevant for me.
As you've mentioned, if you ever need to install Codeigniter in a subdirectory, the / leading forward slash will of course not work. You would have to include the subdirectory name in the path. Personally, this comes up a lot because we'll install redesigns or prototypes in sub-directories. However, this can be nice (if it's applicable) for switching to SSL if you aren't already letting CI auto-detect your base url (as of v2.0.2).
Changing your $config['base_url'] to not include the full domain can be a bad idea. Off the top of my head, this would break links and references in emails sent by your application that use the base_url() function, and in general is likely to cause unexpected results.
Almost every HTML tag you need to use your base url in, like <link> <img> and <a>, is covered by a Codeigniter function. (link_tag(), anchor(), img()). These will take care of the base url for you. (Why they left out <script> is beyond me...)
However, I agree - using the full base url adds a lot of unnecessary page weight, especially in your navigation. Here's what I do to grab the path (in case of sub-directory installs):
// constants.php
$base_uri = $_SERVER['SCRIPT_NAME']; // Always index.php (bootstrap), right?
$base_uri = str_replace('index.php', '', $base_uri);
define('BASE_URI', $base_uri);
You can change this to a function or config item or whatever, I prefer a constant. Then you can use:
<script src="<?php echo BASE_URI; ?>js/functions.js"></script>
This will usually be a long-winded way to say /, but handles the sub-directory issue.
This might seem like a waste of time, but when you have lots of installations using the same codebase, less configuration is better.
As a compromise between readability and flexibility I would do the following:
<link rel="stylesheet" href="<?= site_url('css/main.css') ?>" />
<script src="<?= site_url('js/jquery.js); ?>"></script>
<script src="<?= site_url('js/functions.js); ?>"></script>
...
<img src="<?= site_url('images/dolphin.png'); ?>" />

PHP Include Paths

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.

Categories