0

The idea is to store the base address of the Test Website, which is essentially a subfolder within the main domain (eg: www.mydomain.com/mywebsite/). It is not difficult to get this string value. I just have to use $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'] in the index page.

But what I want is to store this value and use it to include other files. So it doesn't make sense to include a file storing the variable to get the full path. I want to use it as, something similar to $_SESSION["someName"]. The problem with this is that, for security reasons, I wrapped the session_start() in a function secure_session_start(), which is in another file and needs to be included before being called.

So, in short, I need to get the value of this variable before even a single file is included() or required(), after it was once set from the 'index.php' page.

If I could use the session_start(), It would have been possible to store in the $_SESSION. But I can't...

EDIT:-

Here's the hierarchy of files:

enter image description here

Now here Public_html points to WWW.MYDOMAIN.COM. That is my website.

I am currently creating a website for my client: WWW.CLIENTWEBSITE.COM. But I'm hosting it only after the website is completed. But for now, the client can see the progress through, WWW.MYDOMAIN.COM/CLIENTWEBSITE/

So when I'm developing the website, I need to either use 'relative paths' (eg: ../somefolder/something.etc) or I can use the 'WWW.MYDOMAIN.COM/CLIENTWEBSITE/' to prefix the url's for include, require, etc. But it will change, once I host it on their domain to WWW.CLIENTWEBSITE.COM. But I don't want to end up changing each and every url's in all the pages. So I want a variable with somewhat a super-global scope which can store this base-url, that I need to change it only once.

I've been experiencing few problems with Relative paths. So, I want to use the full URL to link to a file. That is the reason why I had this question raised.

Problem I'm facing on Relative Paths: (This is not the actual question, but I'm extending it)

index.php

<?php
include_once 'includes/bootstrap_functions.php';

/* ...functions following it... */

bootstrap_functions.php

<?php
include_once "../common/dbhandler.php";

function someDBFunction(){
    global $DBH;
    .
    .
    .
/* ...functions following it... */

dbhandler.php

<?php

include_once "psl-config.php";

$DBH = new PDO("mysql:host=".HOSTNAME.";dbname=".DBNAME, DBUSER, DBPASS);

/* ...functions following it... */

psl-config.php

<?php

define("HOSTNAME","localhost");
define("DBNAME","somename");
define("DBUSER","someuser");
define("DBPASS","somepassword");

And then when I run index.php, I get this:

enter image description here

BlackPanther
  • 1,732
  • 1
  • 14
  • 19
  • I don't know what your problem is, you can just include the file at the top of your script. – Charlotte Dunois Aug 03 '14 at 13:48
  • The variable he wants to set contains the path used to find all include files, so that's a chicken-and-egg problem. – Barmar Aug 03 '14 at 13:49
  • If his file which includes his domain is in the same directory like his index.php, there is no problem with using include. – Charlotte Dunois Aug 03 '14 at 13:51
  • It wouldn't even be a problem if it's in a subdirectory. – Charlotte Dunois Aug 03 '14 at 13:51
  • 1
    Also you shouldn't use the domain to include files. Use the relative or absolute filepath. `$absolute_path = dirname(__FILE__);` – Charlotte Dunois Aug 03 '14 at 13:55
  • @Charlotte Dunois That's surprising, I read somewhere that, the most foolproof way would be to use a full domain name included url...!! after all the base url for this 'test website' is something like, 'www.mydomain.com/mywebsite/'. Will I get the absolute path as '/mywebsite/'? – BlackPanther Aug 03 '14 at 14:16
  • I do know many ways to use the url if 'include' is allowed. From DB, $_SESSION, or whatever. But none of these appear to be the straight approach... :( – BlackPanther Aug 03 '14 at 14:17
  • Hey @Barmar.. what have you done? these questions are not the same. I don't want to include anything...!!! – BlackPanther Aug 03 '14 at 14:23
  • If the value is fixed for the whole project, you could set it as an environment variable in your Apache configuration. This is quite a popular approach for application configuration directives. – halfer Aug 03 '14 at 14:24
  • @BlackPanther Yes, if you want to embed images, javascript or css files. But not serverside scripts. You wouldn't even include the script itself if you're using the domain. You would include the output of the script. – Charlotte Dunois Aug 03 '14 at 14:27
  • @BlackPanther No, that's just the subdirectory of the root directory. An absolute filepath is something like `/var/www/testwebsite/script.php`. – Charlotte Dunois Aug 03 '14 at 14:31
  • Thanks for the comment. But I want the subdirectory of that root directory, where the whole website is residing. Say, mydomain.com, has an index.php. But it is just for mydomain.com. I have a website clientdomain.com to make. So I give a preview to the Client through 'mydomain.com/clientdomain/'. But when I deploy that website. I dont have to end up manually changing all the links or urls in each and every page. Wordpress does this using DB. – BlackPanther Aug 03 '14 at 14:38
  • I found another option, use 'setcookie("root","/mydomain/");' and then use 'echo $_COOKIE["root"];' later where I needed it. This works brilliantly, but is not at all secure for sensitive data. Thanks to @Barmar , I cannot post this as an answer...!!! – BlackPanther Aug 03 '14 at 14:54
  • But where will you run `setcookie` if you don't include the file first? – Barmar Aug 03 '14 at 18:48
  • which file? when the website first runs, it would definitely go to the index.php. There I will give setcookie("root","www.mydomain.com/clientdomain/"). Later any page I access, I would be getting that value through $_COOKIE['root']. Am I right or not? – BlackPanther Aug 03 '14 at 19:14

4 Answers4

2

Lots of scripts use a constant for the base URL/path of the original script. Put this before your includes:

define( "URL", $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'] );

Now you can use use within those files, and they can't change it.

$img = URL . "/image.png";

I'm not sure HTTP_HOST and SCRIPT_NAME are correct for your usage, but that was not the question.

Note: Don't use sessions/cookies to store this. It's just weird. Unless the path was random. If you need this same variable on multiple scripts to be the same, you need a structural change. Consider what might happen if the user lands on a page other than the front page.

UPDATE

A problem was introduced that the script which is defining the URL is not actually in the "document root", and in fact the domain changes from localhost to example.org.

Note: I am unable use mydomain dot com in this answer. Using example.org instead!

If your script is in a subfolder, you have two options. Navigate up two folders using dirname or remove the subfolder via str_replace. The first option is less likely to break if you rename your folders/scripts in the future.

Input: http://example.org/subfolder/include/common/common_functions.php
Target http://example.org/subfolder/

Option 1: Up two folders (and strip filename)

$siteurl = 'http://' .  $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
$siteurl = dirname($siteurl); // removes "common_function.php"
$siteurl = dirname($siteurl); // removes "common/"
$siteurl = dirname($siteurl); // removes "include/"
define( "URL", $siteurl ); // result: http://example.org/subfolder/

Option 2: Removing relative filename

$siteurl = 'http://' .  $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
$siteurl = str_replace('include/common/common_function.php', '', $siteurl);
define( "URL", $siteurl ); // result: http://example.org/subfolder/

In both options, we use $_SERVER['HTTP_HOST']. By this answer's definition, HTTP_HOST is the hostname that the visitor sees. This should be localhost for you, and example.org for your client. I encourage you to test this yourself.

In both options, the use of $site_url is completely optional, so that it is easier to read. You can combine these if you don't like clean code:

define( "URL", dirname(dirname(dirname('http://' .  $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] ))) );

Paths VS URLs

My above examples are using URLs. These are what you send to the browser, especially for images, javascript and CSS files. eg: <img src="<?php echo URL; ?>/images/my-image.png">.

If you are including other scripts, you do not want to use a URL. You want a path instead.

$sitepath = __FILE__; // /var/www/example.org/include/common/common_functions.php
$sitepath = dirname( $sitepath ); // removes common_functions.php
$sitepath = dirname( $sitepath ); // removes common/
$sitepath = dirname( $sitepath ); // removes include/
define( "PATH", $sitepath ); // /var/www/example.org/

Using your path may not even be necessary, but you may define it:

include( PATH . '/include/common/another-script.php' );
// Alternatives relative to current script:
include( 'another-script.php' ); // When the current script is in the same folder
include( 'common/another-script.php' ); // Current script is in the "include" folder
include( '../rare/another-script.php' ); // "rare" folder is next to "common", current script is in "common"
Community
  • 1
  • 1
Radley Sustaire
  • 3,382
  • 9
  • 37
  • 48
  • Yes that's the kind of answer I'm looking for... At least its close. But what I meant by the 'base_url' is something like this : 'www.mydomain.com/subfolder/' . This cannot be achieved from the code above, within 'www.mydomain.com/subfolder/include/common/common_functions.php', can it? I need to get the exact string 'www.mydomain.com/subfolder/' there too, so I can use it to include or redirect to files in other directories. – BlackPanther Aug 03 '14 at 19:35
  • Look at the answer, I found, below. Hope that gives you an idea. That is eligible for an accepted answer. But I'm not sure that's the best I can get from here... – BlackPanther Aug 03 '14 at 19:39
  • I've expanded my answer to support your "parent folder" structure. It should work for both localhost or a custom domain name. – Radley Sustaire Aug 04 '14 at 19:01
  • I've also added paths, which may be what you really want. Or not. You pick. – Radley Sustaire Aug 04 '14 at 19:10
  • 1
    I'm really grateful that you are taking this seriously. But still, that is not what I want. May be it's the problem with my English. But I can't see a better way to explain it. All I wanted to do was to get the location of 'index.php' and make it available in all the other pages without repeating the same set of codes, or at least repeating just a single line of code in all the pages. This has just made it a whole lot complicated. Please, you don't need to write down any code. You just have to give me any idea of doing it. I never ask for codes on StackOverflow. I'm not a nube. – BlackPanther Aug 05 '14 at 04:29
  • I'm aware that I can get the url in any way I want, form $_SERVER[] and a few url string manipulators. I'm not asking for an escape path. I'm asking for a solution. I'm just 23yrs old. I have a long programming career to follow, where I can use these tips. – BlackPanther Aug 05 '14 at 04:33
  • Oh okay, so it sounds like you want the same initial script file to be loaded by any PHP script. You can do this with the `.htaccess` file in the website root folder. This is pretty common, but the main caveat is that the "routed script" will need to handle the request URL. Here is an htaccess example: http://stackoverflow.com/questions/9694118/rerouting-all-php-requests-through-index-php – Radley Sustaire Aug 05 '14 at 04:40
  • BTW There are plenty more examples online, just search for "route all requests through index.php with htaccess" or something similar. – Radley Sustaire Aug 05 '14 at 04:41
  • Nope. That won't be the problem. I already knew that. That is why I've used the `setcookie()` only on my index page. By the way, this project does not have a retained cookie or session that will allow any one to go to any other page without signing-in. So, it always starts from the 'index.php', where the cookie is set for the root url...! The thing is I could use a better method. – BlackPanther Aug 05 '14 at 04:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58654/discussion-between-blackpanther-and-radgh). – BlackPanther Aug 05 '14 at 04:52
0

You can configure an auto_prepend_file using the php.ini directive that will automatically be included before every web request

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • I'm not much of a server admin. I do a lot of freelance works. All of these are hosted in subfolders under a single domain. So, should I really play with php.ini?\ – BlackPanther Aug 03 '14 at 14:19
  • .htaccess or its local equivalent should also let you set those values. – Jason M Aug 03 '14 at 19:06
0

Here's one option I found, use setcookie("root","www.mydomain.com/subfolder/"); and then use echo $_COOKIE["root"] later wherever you needed it, irrespective of the page.

This works brilliantly, but is not at all secure for sensitive data.

The negative with this method, is that the cookie will be sent along with all types of communications between the client and server, which makes page loading slower, especially if the cookie is storing some big data (eg: image)

BlackPanther
  • 1,732
  • 1
  • 14
  • 19
  • I think that’s going to be pretty flaky. You’re relying on the browser to keep track of a critical server variable. Especially problematic if the browser isnt’t keen on cookies. – Manngo Mar 20 '19 at 10:26
0

Quoting what is said at Best Practices in PHP :

Making your application location independent

PHP has problems in some situations when include files are nested and reside in different folders and it is unclear at which directory level the file will be included. One can solve this by using absolute path names or using $_SERVER['DOCUMENT_ROOT'] as a starting point. However this makes your code location dependent - it will not run anymore if you move it down your directory structure one level. Of cource we do not like that. I have found a convenient solution to this problem. The toplevel page (the one that is called by the browser) needs to know the relative path to the application root directory. Unfortunately there is no such function in PHP and the webapp context concept is completely absent in PHP. So we can not automatically determine the application root reliably in all situations (It is really impossible. Don't even try. It's not worth the effort.) Let's define a global variable called $ROOT in an include file in every directory that contains toplevel pages. The include file (call it root.inc.php) must be included by the page logic before any other include files. Now you can use the $ROOT variable to reference include files with their exact path!

Sample: We have toplevel pages in /admin/pages/. The $ROOT variable must therefore be set to $ROOT = '../..';. The page logic included by pages in that folder would reference their include files like require_once("$ROOT/lib/base.inc.php");

This sure uses include, and the file is repeated in all the directories, but is a rather useful way. The first paragraph explains the exact kind of dilemma I'm in. The second paragraph is a good way to make sure you can use the same code in all the php files I'm using and still have the freedom to move the files around in different directories, rename the directories, or even change domains... Pretty simple but effective!!

I did have a thought of putting the 'root address' in a file near the index.php file. But to include that, you still need to know the location of the current file. I never thought of repeating the file in all directories.

Community
  • 1
  • 1
BlackPanther
  • 1,732
  • 1
  • 14
  • 19