linking to php includes - php

I'm using a PHP include for my header/navigation, but some pages are unable to find that file. I'm using a root-level link
<?php include("/includes/masthead.php"); ?>
but pages outside of the root folder are not locating the masthead file. For instance:
index.php locates and processes masthead.php just fine;
adopt/adoptadog/php returns an error saying the file does not exist.
Is this because PHP doesn't process links in the same way that HTML does, so my root-relative link just isn't being interpreted by the php include function?
I'd like to be able to have a root-relative link work in my include statement so that statement can go into an Expression Web template. The template seems to write the same address in every page regardless of the location of the page. Maybe it doesn't see a link within a PHP tag the same way it does in HTML--I don't know.
I hope this is clear. Any help?

You could use the document root as the anchor:
include $_SERVER['DOCUMENT_ROOT'] . '/includes/masthead.php';
If your included files are one level outside of the document root, you just need to move with it:
include dirname($_SERVER['DOCUMENT_ROOT']) . '/includes/masthead.php';
If you have a script that gets loaded by all your pages that resides on the document root itself, you can use a constant:
define('PROJECTDIR', dirname(__FILE__));
To include the mast head:
include PROJECTDIR . '/includes/masthead.php';

Try putting this at the top of your script:
set_include_path(get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT']);
Or go to your php.ini file and update the include_path directive to always search your webroot directory.

Related

File path error with forward slash at beginning of path

I have a folder with a bunch of articles that all use the same header and footer, which are in an includes/ folder. I also needed to add another file that is not an article and I therefore do not want it in the folder with the other articles, but instead in the includes/ folder. I still want it to use the same header and footer as the articles though, so naturally I just use a command like
include 'article_header.php';
The error is inside the header, which has include commands inside of it. Because the article_header.php file is built for the articles, the include commands inside of it look like the following:
<?php
include 'includes/article_social_container.php';
include 'includes/article_search_container.php';
include 'includes/membership_container.php';
?>
Since this obviously is not going to work for the file inside the includes/ folder. So I tried using a forward slash and starting from the root directory so it works for any file that uses it.
<?php
include '/root/folder/includes/article_social_container.php';
//other code
?>
However, this does not seem to work. I have had trouble with the forward slash at the beginning of a file path in the past, but it has also worked for me other times.
Also, why wouldn't someone always use a forward slash and start at the root directory, just to keep things safe? It probably is the answer to this question because it seems totally sensible to me unless it was for a similar purpose of the open_basedir() function in php.
Thanks a lot for any help.
Take a look at the __DIR__ magic constant. It resolves to the directory of the script in which it appears. Using this, you only need to use relative paths, for example...
// within the "includes" directory
include __DIR__ . '/article_social_container.php';
Another option is to configure your application's include_path. Say you have a script bootstrap.php in your includes directory with the following...
set_include_path(implode(PATH_SEPARATOR, [
__DIR__, // the "includes" directory
get_include_path()
]));
This will add the includes directory to the top of your include_path stack. You can then simply do the following from any other script...
require_once __DIR__ . '/relative/path/to/includes/bootstrap.php';
include 'article_header.php';
Any included scripts from this point on will have the same include_path configuration so they in turn can simply use...
include 'article_social_container.php';
include 'article_search_container.php';
// etc

PHP require path - same directory

I have index.html in the root and all supporting files in /HTML. I have Google analytics code in a file in the HTML directory. It works from my index.html with this code in between the head tags...
<?php
require('HTML/GoogleAnalytics.html');
?>
but not in any of the supporting files in the HTML directory, same directory as the file i'm trying to require/include with this code...
<?php
require('GoogleAnalytics.html');
?>
from PHP.net "...include will finally check in the calling script's own directory and the current working directory before failing"
What am I doing wrong?
From PHP 5.3 (which is at this time after end of life cycle) and later you can use also __DIR__ constant , http://php.net/manual/en/language.constants.predefined.php
require(__DIR__ . '/GoogleAnalytics.html');
To make it relative to the current file, you can prepend dirname(__FILE__) like so:
require(dirname(__FILE__) . '/GoogleAnalytics.html');
By default, paths are relative to the file that the request originated from.
Try using this:
require('/HTML/GoogleAnalytics.html');

Why would I use dirname(__FILE__) in an include or include_once statement?

I have seen this:
<?php
include( dirname(__FILE__) . DIRECTORY_SEPARATOR . 'my_file.php');
?>
Why would I ever need to do this? Why would I go to the trouble of getting the dirname and then concatenating that with a directory separator, and a new filename?
Is the code above not equivalent to this:
<?php
include( 'my_file.php' );
?>
??
The PHP doc says,
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.
Let's say I have a (fake) directory structure like:
.../root/
/app
bootstrap.php
/scripts
something/
somescript.php
/public
index.php
Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.
Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.
There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)
dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.
(Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)
Now, why not just use include 'init.php';?
As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).
Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?
I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:
Project root directory:
file1.php
file3.php
dir1/
file2.php
(dir1 is a directory and file2.php is inside it)
And this is the content of each of the three files above:
//file1.php:
<?php include "dir1/file2.php"
//file2.php:
<?php include "../file3.php"
//file3.php:
<?php echo "Hello, Test!";
Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!
The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).
Now, what should we do ?!
Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!
So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!
The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!
So now if we turn the project above to this:
//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");
//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");
//file3.php:
<?php echo "Hello, Test!";
if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).
It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!
Hope that helps.
I used this below if this is what you are thinking. It it worked well for me.
<?php
include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>
What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.
If you want code is running on multiple servers with different environments,then we have need
to use dirname(FILE) in an include or include_once statement.
reason is follows.
1. Do not give absolute path to include files on your server.
2. Dynamically calculate the full path like absolute path.
Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'.
Then attach this variable that contains the path to your included files.

Require file including variable

I am currently using the following code to include a file in my webpage:
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/file.php';
However, I have now edited my system so I input the URL into a data file in the root which makes other parts of my site function and allows me to use different directories.
In short, I am using a splash page on a website, where the root is now /directory rather than in the root, thus the URL in my data file is http://www.domain.com/directory.
So, what I need to work out is how to point this line at the directory using the variable from the data file which contains the URL
So $_SERVER['DOCUMENT_ROOT'] becomes irrelevant because I need to grab the data from the variable in the data file which is NOT in the root anymore.
It needs to be something like:
require_once (variable from file a few directories back) + absolute path to file;
I want this line of code to be future-proof too, if I need to build a site using a different directory then the root.
I hope that makes sense!
Create a SITE_ROOT and use that instead. That way, it will work with any directory change.
define('SITE_BASE', '/directory/');
define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'] . SITE_BASE);
You can then use SITE_BASE for creating your URIs:
link
and SITE_ROOT for accessing files on the system:
require_once SITE_ROOT . 'include/file.php';
Have you considered setting include_path in your php.ini file? For instance, my own php.ini file has include_path = ".:/path/to/web/root", which allows me to not worry about where my files are when including them.
In your case, you would want to set it to include_path = ".:/path/to/web/root/directory". If you don't know the path to the web root, just run echo $_SERVER['DOCUMENT_ROOT']; to find it.
This solution is "future-proof", as you only need to change that php.ini value and everything falls into place.

How to include file from another directory

In the root (www) I have two folders.
In the first folder, "folder1", I put a file called register.php.
In the next folder, "folder2", I put files called header.php and footer.php.
I need to include the header and footer files from folder2 in the register.php file.
How can i do this? I tried to use this include ../folder2/header.php
..but it does not work
On some configurations, adding ./ (current dir) does the trick like this:
include './../folder2/header.php';
Alternatively, you can specify in terms of document root:
include $_SERVER['DOCUMENT_ROOT'] . 'folder2/header.php';
<?php include( $_SERVER['DOCUMENT_ROOT'] . 'folder2/header.php' ); ?>
include $_SERVER['DOCUMENT_ROOT'] . '/folder2/header.php';
would work from any directory of the site
it is called absolute path and it's the only reliable way to address a file
However, in real it should be something like
include $_SERVER['DOCUMENT_ROOT'] . '/cfg.php';
// some code
include $TPL_HEADER;
using a variable, previously defined in cfg.php
However, it may fail too. Because you can be just wrong about these paths
And here goes your main problem:
but it does not work
There is no such thing as "it does not work"
There is always a comprehensive error message that tells you what exactly doesn't work and what it does instead. You didn't read it yourself, and you didn't post it here to let us show you a correct path out of these error messages.
include files should generally be kept outside of the server root.
lets say your setup is;
www/website1
and
www/includes
Then you php.ini file, or .htaccess file should stipulate that
include_path=www/includes
then from any of your files, in any directory, no matter how far down the trees they go you simply do:
include 'myfile.php';
where myfile.php is at www/includes/myfile.php
Then you can stop worrying about these issues
include dirname(__FILE__).'/../folder2/header.php';
Try This it is work in my case
<?php require_once __DIR__."/../filename.php";?>
As the PHP manual states here $_SERVER['DOCUMENT_ROOT'] is "The document root directory under which the current script is executing, as defined in the server's configuration file." For this example, $_SERVER['DOCUMENT_ROOT'] will work just fine but. . . By using the new "magic constants" provided in >= PHP 5.3, we can make this code a little safer.
Put your includes in a subfolder, and use the magic constant DIR to make a reference to the included files. DIR returns the directory of the currently executing php file. By using this, you can move your folder containing all your includes anywhere you like in your directory structure, and not need to worry if your includes will still work.

Categories