I'm working on a project. It's a control panel to manage a website. The folder structure is like this:
I set some settings in my config file, some of those are:
$site_url = $_SERVER['SERVER_NAME'];
define ('ABSPATH', 'http://'.$site_url.'/cpanel');
So, my question is: How can I load all resources (images, css, js) relative to the ABSPATH
constant, and all <a>
tags?
With this, I could move the "cpanel project" to an other directory level and it would still work. Like a Wordpress Blog, only setting the Blog URL..
There are several ways to do what you are saying, but one of the most simple one is to use the BASE tag.
<head>
<base href="http://www.yoursitewithimages.com/folder-with-files/" target="_blank">
</head>
Then you can just use
<img src="img/image.jpg">
and it will be read as
<img src="http://www.yoursitewithimages.com/folder-with-files/img/image.jpg">
More info here http://www.w3schools.com/tags/tag_base.asp or here http://www.w3.org/TR/html-markup/base.html
Wouldn't you just do something like this in your php view?
<script type="text/javascript" src="<?= ABSPATH ?>/my_js_file.js"></script>
<link rel="stylesheet" type="text/css" href="<?= ABSPATH ?>/my_css_file.css">
<img src="<?= ABSPATH ?>/my_image_file.jpg" />
This way, you could move the directory anywhere within your docroot and just change the value of ABSPATH
in your config file.
You are probably best served defining several different variables, as having a URL is not going to be useful for purposes of includes and such. You can do something like this:
DEFINE(HOST_NAME, $_SERVER['SERVER_NAME']);
DEFINE(WEB_SERVER_ROOT, $_SERVER['DOCUMENT_ROOT']);
DEFINE(APP_ROOT, __DIR__);
DEFINE(URI_BASE, str_replace(WEB_SERVER_ROOT, '', APP_ROOT);
if ($_SERVER['HTTPS'] == 'on') {
DEFINE(PROTOCOL, 'http');
} else {
DEFINE(PROTOCOL, 'https');
}
DEFINE(URL_BASE, PROTOCOL . '://' . URI_BASE);
For includes you could then do something like:
include(APP_ROOT . '/modules/somefile.php');
For outputting image, javascript, css, etc. links you could use something like:
<img src="<?php echo URL_BASE; ?>/images/someimage.jpg" />
<a href="<?php echo URL_BASE; ?>/somepage">Some Page</a>
<script type="text/javascript" src="<?php echo URL_BASE; ?>/js/somejs.js" />
Here is an alternative based on Mike Brant's solution.
//APP_ROOT and APP_BASE assumes that the current location of this
//script is located in the root of your application.
//Also assumes that the HOST_NAME is what you want in the URL.
//See https://php.net/manual/en/reserved.variables.server.php for reference
define('HOST_NAME', $_SERVER['HTTP_HOST']);
(empty($_SERVER['HTTPS'])) ? define('PROTOCOL', 'http') : define('PROTOCOL', 'https');
define('WEB_SERVER_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('APP_ROOT', __DIR__);
$appBase = str_replace(pathinfo(__FILE__, PATHINFO_BASENAME), '', $_SERVER['SCRIPT_NAME']);
define('URL_BASE', PROTOCOL . '://' . HOST_NAME . $appBase);