Include php files when they are in different folders - php

Most of my website is in my root directory. And In that directory there is "css", "functions", "images" folder. Everything works fine when I include php files within index.php or any other root file. It includes it fine and executes it fine.
But problem occurres when I made folder "blog". So this is totally new and separate root folder with CMS and its own "root" files. And I try to include css from main root directory or some php files from "functions" folder in main root directory, Everything breaks down. I know I have to include it as ../functions/myfile.com. But this files includes some other files so it just wont work properly and won't be able to include other files properly.
Is there any idea how to fix this problem?

You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.
Site 1
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';
Includes under site one would be at:
echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';
Site 2
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';
The actual code to access includes from site1 inside of site2 you would say:
include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');
It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:
//(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');
Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.
Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:
<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>
You should use:
<a href='/contact/'>Contact</a>
For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:
User-agent: *
Disallow: /blog/
Other possibilities:
Look up your IP address and include this snippet of code:
function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';
if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}
if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}
Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.
If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:
if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}

If I understand you correctly, You have two folders, one houses your php script that you want to include into a file that is in another folder?
If this is the case, you just have to follow the trail the right way.
Let's assume your folders are set up like this:
root
includes
php_scripts
script.php
blog
content
index.php
If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:
include("../../../includes/php_scripts/script.php");
The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.

i had the same issue and found a code on https://css-tricks.com/php-include-from-root/ that fixed it
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/common/header.php";
include_once($path);
?>

None of the above answers fixed this issue for me.
I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>

Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

Related

include_once in header breaks when an absolute path is used

I have my website on my local server (localhost - XAMPP). My website is broken up into three parts: 1)Header 2)Body and 3)Footer/Jscripts.
The header.php calls other basic files for the header section of the webpage. It works fine when I used relative paths, for example: include_once('./_css/main.css'); to call my CSS files or include_once('./_inc/metadata.php); to call my metadata for my pages.
The problem arises when I use an absolute path:
include_once('http://localhost/mywebsite.com/_css/main.css'); the same for the other files.
Why is that? This all started because I want to create subfolders because I had a general page, but now that I'm breaking it down to subpages I need a folder to contain the subpages
I was trying to include the css files and all the other resource files to the subpages, but they break using the relative paths method (./_css/main.css) being pulled from the header file located in the root directory. On the subpages, I'm using include_once('../_inc/header.php') to include the initial header.php file.
I want to avoid having to duplicate all the resource files from the root directory and adding them in the subfolder with their respective relative paths. That's why I was trying to use the absolute path method.
Any insight or clue would be appreciate as to:
Fix the 'Warning: include_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0' error when using the absolute path.
2)Sharing css files in subfolders.
Using an absolute path may be a bad idea, what if you move from localhost to a real server? You'd need to make massive changes. Changing the project structure so that you could avoid all of this might be better, or if you really want to keep things as they are, use a variable.
<?php
$include_path = "whatever/path"
include('../header.php');
?>
and in header.php
<?php
include($include_path.'/my_css.css');
?>

How to include a php file in subdomain from main domain

I have two folders in my server:
--MainDomain
-header.php
-index.php
-footer.php
--Subdomain
-index.php
Now I want to include header.php from main domain in index.php which is in sub domain.
By using the include function I get the error
failed to open stream: No such file or directory in /home/content/xx/xxx/xxxx/xxx/
I know that this error occurs when a file does not exists on the given mentioned path, but how can I include a file from main domain to sub domain?
thank you in advance
I know this question was asked eight months ago, but I've just had this same exact problem and solved it. Hopefully this will help people in the future who stumble across the same thing.
For example, let's say you have two subdomains: carrot.cake.com and chocolate.cake.com
You have a file in the carrot subdomain: carrot.cake.com/scripts/login.php
And you have a file in the chocolate subdomain: chocolate.cake.com/index.php
You want to include the file "login.php" inside of the file "index.php".
The important part is that this IS possible but it's possible ONLY if you do store the files of both of these domains on one single server filesystem.
Add the following code to your index.php file:
<?php
echo '<br>'.$_SERVER['DOCUMENT_ROOT'].'<br>';
?>
And then go load up your index.php file in a browser. It will show you what your actual directory folders are. For example, when I did this, it showed me that my filesystem looked like:
/home3/cake/public_html/chocolate_domain
Yours will be DIFFERENT FROM MINE, so test that php code snippet out, yourself. And delete that code right afterwards. It is just for testing purposes. But now you know how to actually access all the folders to all your domains. This means that your index.php file is in, for example,
/home3/cake/public_html/chocolate_domain/index.php
and that your login.php file is in, for example,
/home3/cake/public_html/carrot_domain/scripts/login.php
Now, for the final result! If you want to include "login.php" inside of "index.php", then you should put the following code into your "index.php" file:
<?php
include("/home3/cake/public_html/carrot_domain/scripts/login.php");
?>
Please remember, once again, that the actual path for YOU is different, so test it out using the echo of the document root, like I said before~
good luck~
Here is a tidy way to do this.
An include from a subdomain:
include( $_SERVER['DOCUMENT_ROOT'] . "/../exampledomain.com/filetoinclude.php" );
This gets the whole path to your file, and then regardless of the subdomain you are in, it will jump up to the folder above that and call "exampledomain.com" domain. This saves showing your folder hierarchy to anyone who sees that file.
You could also reverse this
an include to a subdomain:
include( $_SERVER['DOCUMENT_ROOT'] . "/../sub.exampledomain.com/filetoinclude.php" );

Find filepath to public_html directory or it's equivalent using PHP

I'm creating a .php file that will be uploaded to the root directory of a server. I need that .php file to then figure out the path to the public_html folder or it's equivalent.
I need to do this because I want my .php file to be able to be uploaded to the root and used on any hosting account. Because many hosting companies use different file paths to the public_html folder or even call it something different, I'm trying to figure out how to detect it.
Preferable there is a server variable or easy test to do this. If not, the public_html folder will always contain a particular file so maybe I could search for this particular file and get the path that way. I'm just worried about a filename search being heavy on memory.
The .php file that is being executed is located inside the ROOT directory and needs to locate the public_html folder.
Like this: /home/user/file.php
needs to detect
/home/user/public_html/ or /home/user/var/www/ or /home/user/website.com/html/ etc.
The challenge with this is that a server can have very many public_html's so outside of the context of a request there is no real way to find out what that is.
One thing that you might be able to do to get this information from a php script (if you know the url to get to the host) is to create a php file called docroot.php that looks like this.
<?php
if ($_SERVER["REMOTE_ADDR"] == '127.0.0.1'){
echo $_SERVER["DOCUMENT_ROOT"];
}
Then within your file.php your would do something like
$docRoot = trim(file_get_contents("http://www.mydomain.com/docroot.php"));
This makes the assumption that the server can resolve to itself via the local interface by name.
I found this website which provided me with the only good solution I have found after scouring the web...
$root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", "", $_SERVER['SCRIPT_FILENAME']);
The way this works is by getting the full path of the file and then removing the relative path of the file from the full path.

How can I control DOCUMENT_ROOT to work on localhost and live server?

To keep URLs working in version-controlled projects, I've been using $_SERVER['DOCUMENT_ROOT']. The problem is, I develop projects within a folder, so I get this:
$_SERVER['DOCUMENT_ROOT'] . '/folder/path/to/file.php'
When I go live, I generally simply want the following:
$_SERVER['DOCUMENT_ROOT'] . '/path/to/file.php'
I know there are bigger problems in the world than having to remove and add this folder name, but is there a way I can easily automate this? Can I somehow set my document root locally to include the folder I'm working in? Do I have a fundamental misunderstanding of the way things are working? Kind of new at this stuff, and looking to learn as much as possible and really grok the "why."
Thanks so much!
Instead of using $_SERVER['DOCUMENT_ROOT'], why not declare a constant which always holds the root of your web application?
<?php
define('ABSPATH', dirname(__FILE__));
Put the following code in a file located in the root folder of your application and include it on every page load.
Then, you can simply always do $path = ABSPATH . '/path/to/file.php'; regardless of if your local copy is in a sub-directory folder or not.
If your application already has a file which is included on every page load, you can simply drop the code above in that file and it will work.
Just note that you may have to add additional dirname() calls depending on where that file is located. Add one for each directory you pass from the root of your webapp.
For example, if your webapp is located in /webapp/ and your "global include" is located in /webapp/includes/framework/init.php, then the above code needs to be modified as such:
define('ABSPATH', dirname(dirname(dirname(__FILE__))));
ie.: 2 additional dirname() calls due to two additional folders from the webapp root (includes/framework)
Clarification
The code above is meant to be in one file, and one file only in your web application. That file needs to be included on each page load.
If you already have a file which is included before any processing (such as a configuration file or other), you may copy and paste that code in that file.
The number of dirname() calls depends on how deep the file you copied and pasted the
code in is relative to the root directory of your web application. For the examples above, assume the root of your web application is represented by ~.
If you copy-paste my code into ~/abspath.php, then you need one dirname() call.
If you copy-paste my code into ~/includes/abspath.php, then you need two dirname() calls.
If you copy-paste my code into ~/includes/config/abspath.php, then you need three dirname() calls. Now let's just say that's its final location.
In ~/index.php, you do the following:
<?php
require_once('includes/config/abspath.php');
and you have access to ABSPATH.
In ~/dir/someOtherPage.php you do the following:
<?php
require_once('../includes/config/abspath.php');
and you have access to ABSPATH.
This is why I'm saying that if you already have a file which is included on each page load, its simpler just to drop the above code in it. Just make sure you modify the amount of dirname() calls accordingly. Again, this code is meant to be in ONLY ONE FILE.
declare below line in any of root file (index.php)
$_SESSION["uploads_base_url"]=dirname(__FILE__);
and you can now use this in any of file where uploads needed.
echo $uploads_base_url=$_SESSION["uploads_base_url"];

Absolute Relative path issues in referencing web assets - need help - php related

Hi guys I'm in a bit of a pickle here now. Well to start with I built a simple CMS in PHP with an admin panel the directory structure is like this:
root/
->admin/
->images/
It worked fine as is however the client requirements changed and they wanted that instead of having to access the admin folder as a folder within the root it be accessed as a web subdomain. so www.site.com/admin becomes admin.site.com
However this has terrible messed up and destroyed practically all the referencing I had done. Like I upload images on the CMS - however now uploading on ../images doesn't work as its now under a subdomain and I'm all messed up in trying to relatively reference images from there too. I've been trying to hack away at my config file for weeks and can't get to fix this :( - help please - on the front end the site is o.k. but my admin section is all messed up :(
I'm using PHP and MySQL.
Sounds like you've learned how toxic relative paths can be.
Possible quick fix: what happens if you copy/symlink/alias admin.domain.com/images to point at the same images folder that lives on your front-end site? I think that extra "../"es will basically be ignored.
More permanently, and in general, don't use relative paths. They will cause you nothing but pain. A couple of strategies:
1) Define some constant that points at the right location for images, css, etc:
define('IMG_DIR','/images');
define('CSS_DIR','/images');
// ... some time later
echo '<img src="' . IMG_DIR . '/myimage.jpg'"/>';
2) Much better: just maintain one constant that tells you where your application lives.
define('APP_ROOT','/myapp'); //could be chanted to just '/' if it doesn't live in some folder on the server
// ... later that day ...
echo '<img src=\"' . APP_ROOT . '/images/myimage.jpg"/>';
// ... or maybe you need to link to a logout script?
echo 'Log Out';
It's important to assume you application might need to run from the root ("/") or some directory on the server, etc.
The same goes for any filesystem operations you might do purely on the server side. Use absolute filesystem paths. If your main application has a script like "config/config.php", you could stick this at the top:
define('APP_FS_ROOT',realpath(dirname(__FILE__) . '/..'));
Assuming both the frontend and the admin are on the same file system, you will need to use absolute paths for everything in the admin. In the admin's config create a define that maps to the frontend's physical upload/image folder. For example, from the fontend you can access uploads folder with the relative path ./upload but from the admin.example.com site you will be required to use the absolute path /user/example.com/upload.
The fontend's config would look like (www.site.com/config.php):
define("UPLOAD_FOLDER", "./uploads");
define("WEB_UPLOAD_FOLDER", "/uploads");
The admin's config would look like (admin.site.com/config.php):
define("UPLOAD_FOLDER", "/user/site.com/upload");
define("WEB_UPLOAD_FOLDER", "http://www.site.com/uploads");
Then both the frontend and admin would reference the physical folder with:
$filename = UPLOAD_FOLDER . "/myupload.mp3";
And to create hyperlinks to the upload you would use this:
My Upload
Another possible solution would be to define a directory alias in apache for the directories you've moved.
Lets say your sub domain root is
/subdomains/images
<VirtualHost>
...
Alias /images "/subdomains/images"
...
</VirtualHost>
Both www.yourDomain.com/images and images.yourDomain.com would load the same files.
Or, if your using linux, a symlink could accomplish the same thing.

Categories