I have the current tree.
/edu/index.php
/edu/Classes/Connection.php
/edu/Classes/User.php
/edu/Handlers/Post.php
When I need to use functions from Connection.php and User.php inside index.php, I require them using:
require_once './Classes/Connection.php';
require_once './Classes/User.php';
But some functions from User.php also needs functions from Connection.php to work, so since index.php is where the requests come from, I require Connection.php inside User.php using:
require_once './Classes/Connection.php';
But sometimes I need to use the same functions from Post.php, so
require_once './Classes/Connection.php'; inside User.php does not work if Post.php is the file sending requests.
Isn't there a unified path or solution so that I can be able to require the file from any place inside my project in the same way? I would really like to avoid a solution such as...
public function UserFunction($path){
require_once $path;
}
And change the parameter on each call depending on my position inside the project folder.
If the files you are trying to include are mostly classes, it would probably be best to implement the __autoload function. When you instantiate a class, if the class hasn't been defined, then the __autoload method is called with the class name so you can include the file. If you create a simple standard, like all classes reside in the $_SERVER['DOCUMENT_ROOT'].'/classes/' folder and the filename is the same as the class name like ClassName.php, you can dynamically load in any classes as they are needed.
Also, generally looked down upon but I figured I would mention it because I hadn't seen it offered yet. There is the set_include_path() function you can call that will allow you to set the path(s) that php looks when including a file. HOWEVER, this can cause some trouble. As an example, my work hosts several sites under sub-domains each with their own document root. Under the document root each site has its own "includes" folder. Well some genius about 8 years ago set the include path in the global apache config to /var/www/site1/includes;/var/www/site2/includes...etc. Problem is that when a file exists with the same name in site1 as site2 and you try to include it, you will always include the file from site1 because php will find the file there and stop looking. It has caused some small headaches from time to time.
Your best best is to include relative to __DIR__ to get a file relative to another file.
Other good points that you can include from are
$_SERVER["DOCUMENT_ROOT"]
or make your own using htaccess.
in .htaccess put
SetEnv MY_INCLUDE_PATH "/path/to/my/php/files";
then in php
include ($_SERVER["MY_INCLUDE_PATH"]."/Connection.php");
Related
Is it possible to "fake" the inclusion of a file ?
I am testing a code base where DI hasn't been implemented and want to include a class file with my own version before it gets required. When it hits the actual require line, I get complaints about the class already being added.
So when I do require_once on the file, I don't want to actually include it, but it to carry on like it did.
You can use include_once() which won't give you breaking errors but will still try and include the file.
My solution was to duplicate the project and change directory before including the configuration files containing require statements: except in the copied directory, the files were empty.
Then I switched back to the current directory.
Okay so on my website I have a scripts folder which includes a php file which connects to mysql server so If I move a database then It will change it on all the files which are connect to the database.
I also have another folder called templates. In that folder there is a top for the header and the footer. In the header template I wrote:
require("../scripts/connect.php");
And I have another folder called, category. And that folder includes the header and the header includes connect. But then it displays and error that there is no such files.
Please help. Thank you
A good practice is to include a main config in all running php files, usually called config.php :)
in this config file create a constant called SITE_ROOT or something similar that point to the exact folder like this
define("SITE_ROOT", "/var/www/mysite");
Then on any include, include_once, require, require_once use it like this:
require(SITE_ROOT."/scripts/connect.php");
This should solve any relative path drama
You shouldn't use relative paths with the include/require, but use a constant defining the ROOT_PATH of your website.
Example:
In all the files calling needing includes:
define(ROOT_PATH, '../');
include ROOT_PATH . '/scripts/connect.php';
And in /scripts/connect.php (and all the other files that will be included somewhere), all the includes should use ROOT_PATH (without defining it).
I have a directory root:
index.php
includes/
template.php
testfile.php
phpFiles/
processInput.php
testfile.php
index.php:
require_once("includes/template.php");
template.php:
require_once("includes/phpFiles/processInput.php")
processInput.php:
require_once("testfile.php")
require_once("../testfile.php")
This code will work when you run index.php, of course it will not work when you run template.php.
As you can see, index.php includes template.php like normal. But in template.php, you have to include like if you are in the directory that index.php is in. But then, in processInput.php, you include as if you are in the directory that processInput.php is in.
Why is this happening, and how can I fix it so that the include path is always the directory of the file that the require is done in? The second included file have the same include path as the requested file, but the next one does not.
Thanks for your help!
EDIT: The strange thing is that I've included classes in a class folder. And it included other files as it is supposed to, even though the paths are relative. WHY does this happen, and how can I fix it?
VERY IMPORTANT EDIT: I just realized that all this is because in my example, the inclusion in includes/phpFiles/processInput.php includes a file in the same directory: require_once("file in same dir.php"); This is the reason. If you are including a file with out specifying anything more than the filename, the include_path is actually the dir where the file the require is written in is in. Can anyone confirm this?
Use an absolute path.
require_once($_SERVER['DOCUMENT_ROOT']."/includes/phpFiles/processInput.php");
Use a similar form for all your required files and they will work no matter where you are.
You can do this in a few ways, amongst others:
Use set_include_path to control the directories from where to perform require() calls.
Define a common absolute base path in a constant that you define in index.php and use that in every require() statement (e.g. require(BASEPATH . '/includes/template.php')).
Use relative paths everywhere and leverage dirname(__FILE__) or __DIR__ to turn them into absolute paths. For instance: require(__DIR__ . '/phpFiles/processInput.php');
By default, the current working directory is used in the include path; you can verify this by inspecting the output of get_include_path(). However, this is not relative to where the include() is made from; it's relative to the main executing script.
You're using relative paths. You need to use absolute paths: $_SERVER['DOCUMENT_ROOT'].
When you include/require, you are basically temporarily moving all code from one file, to another.
so if file1.php (which is located in root) contains:
require("folder/file.php");
and you include file1.php in file2.php (which is in a different location (say folder directory for example):
file2.php:
require("../file1.php");
Now all of file1.php code is in file2.php. So file2.php will look like this:
require("../file1.php");
require("folder/file.php");//but because file2.php is already in the `folder` directory, this path does not exist...
index.php:
require_once("includes/template.php");
template.php:
require_once("includes/phpFiles/processInput.php")
Your directory structure is off. The file inclusion is being seen from the file you're using it from. So, "template.php" is looking for an "includes/" folder in its current folder (/includes/).
As others are saying, use absolute paths, which will make sure you're always going at it from the file system root, or use:
require_once("phpFiles/processInput.php")
In your template.php file (which is far more likely to break if you ever move things around, which is why others all recommend using absolute paths from the file system root).
BTW, if you're using "index.php" as some kind of framework system, you can consider defining a variable that stores the address of common files such as:
define('APPLICATION_PATH', realpath(dirname(__FILE__));
define('PHPFILES_PATH', APPLICAITON_PATH . '/includes/phpFiles/');
I've been writing:
include('a.php')
include('b.php')
etc. in my script to include to use functions a() and b(). It gets pretty tedious. Is there a way to set a path of a directory and have multiple files there be accessible by a script?
I tried this in my script:
set_include_path('.;C:\xampp\htdocs\myfunctionfolder');
And I set an environmental variable PATH to have this older in there.
I also in modified php.ini to include
include_path = ".;\xampp\php\PEAR;\xampp\htdocs\myfunctionfolder"
If I have many files in there, how do I access these files without having to include each individually? Setting the environmental variable definitely works in the command prompt.
Do I need to do something else for .php files to be accessible collectively under a directory?
Common practice is to have a "common.php" or "includes.php" file that includes the include/include_once calls (for the sake of simplicity). e.g.
root
[lib]
a.php
b.php
includes.php
index.php
Then includes.php contains:
<?php
include_once('a.php');
include_once('b.php');
?>
Then in any script it's a matter of including the includes.php file.
However, to answer your original question, you can only include one file at a time, per call. You can use something like opendir and readdir to iterate over all files in a specific directory and include them as found (automated so-to-speak) or write out each include yourself based on the files you're creating.
Also, all setting the include path does is set a directory to look in when an include call is made. It's not a directory where the files should automatically be loaded (which is the impression I get from your post).
Setting the include_path will not include every file in that directory, it only adds that directory to the list PHP will search when including a file.
Specifies a list of directories where the require(), include(), fopen(), file(), readfile() and file_get_contents() functions look for files.
Source
This would simplify including files in a deep structure or in a completely different section of the filesystem.
include('/var/somewhere/else/foo.php');
With /var/somewhere/else/ added to the php.ini include_path could become
include('foo.php');
Additionally, as others pointed out, there are common practices but you could look into OOPHP and autoloading classes. This will not work for functions that I know of.
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
PHP's parser is pretty efficient - you'll waste a lot more time loading a ton of individual files instead of one (or a few) more monolithic files. However, if you insist on keeping things segregated like that, you CAN create meta-include files to load sets of individual files, so you'd only include the one single meta-include file, and it does the rest for you:
meta.php:
include('a.php');
include('p.php');
...
include('z.php');
And then you simply do:
<?php
include('meta.php');
in your scripts and you've got all the individual ones loaded for you.
I have a function like this in most of my projects:
function appendToIncludePath($path)
{
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . BASE_DIR . $path . DIRECTORY_SEPARATOR);
}
see this question:
How to include() all PHP files from a directory?
Also, in terms of best practices, you can include multiple functions in the same file if they are at all related, and I would also suggest having more descriptive names of your functions and files. For example, if your a() and b() functions both related to validation for example, name your file validation.php and put both functions in there and try to rename them to something that is related to what they do. This will allow you to remember what they do when you start piling up a huge list of functions ;)
include __DIR__ . '/../folder1/folder2/folder3/Target.php';
include __DIR__ . '/../folder1/folder2/Target.php';
It helps you go to any path.
Download latest PHP zip and extract to C drive then download composer and install it, during installation it ask for PHP path so just select extracted PHP path.
As follow below step.
Go to Computer.
Select Advance System Settings.
From system properties select Environmental Varaibles.
In Environmental Varaibles add Path in User Variable for PCNAME
In Environmental Varaibles add Path in System Variables.
Hit OK.
Restart PC.
Win + R type cmd.
type command php -v.
Vola you good to go.
PHP
http://php.net/downloads.php
Composer
https://getcomposer.org/download/
I'm having problems with my include files. I don't seem to be able to figure out how to construct my URLs when I use require_once('somefile.php'). If I try to use an include file in more than one place where the directory structures are different, I get an error that the include file cannot be found.
In asp.net, to get my application root path, I can use ~/directory/file.aspx. The tild forward slash always knows that I am referencing from my website root and find the file no matter where the request comes from within my website. It always refers back to the root and looks for the file from there.
QUESTION: How can I get the root path of my site? How can I do this so I can reuse my include files from anywhere within my site? Do I have to use absolute paths in my URLs?
Thank you!
There is $_SERVER['DOCUMENT_ROOT'] that should have the root path to your web server.
Edit: If you look at most major php programs. When using the installer, you usually enter in the full path to the the application folder. The installer will just put that in a config file that is included in the entire application. One option is to use an auto prepend file to set the variable. another option is to just include_once() the config file on every page you need it. Last option I would suggest is to write you application using bootstrapping which is where you funnel all requests through one file (usually with url_rewrite). This allows you to easily set/include config variables in one spot and have them be available throughout all the scripts.
I usually store config.php file in ROOT directory, and in config.php I write:
define('ROOT_DIR', __DIR__);
And then just use ROOT_DIR constant in all other scripts.
Using $_SERVER['DOCUMENT_ROOT'] is not very good because:
It's not always matching ROOT_DIR
This variable is not available in CGI mode (e.x. if you run your scripts by CRON)
It's nice to be able to use the same code at the top of every script and know that your page will load properly, even if you are in a subdirectory. I use this, which relies on you knowing what your root directory is called (typically, 'htdocs' or 'public_html':
defined('SITEROOT') or define('SITEROOT', substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos($_SERVER['DOCUMENT_ROOT'], 'public_html')) . 'public_html');
With SITEROOT defined consistently, you can then access a config file and/or page components without adapting paths on a script-by-script basis e.g. to a config file stored outside your root folder:
require_once SITEROOT . "/../config.php";
You should use the built in magic constants to find files. __FILE__ and __DIR__. If you are on PHP < 5.3 you should use dirname(__FILE__)
E.g.
require_once __DIR__.'/../../include_me.php';
$_SERVER['DOCUMENT_ROOT'] is not always guaranteed to return what you would expect.
Define it in a config file somewhere.
Assuming you're using an MVC style where everything gets routed through a single index.php then
realpath('.');
Will show you the path to the current working directory (i.e where index.php is)
So then you can define this as
define('PROJECT_ROOT', realpath('.'));
If it's not MVC and you need it to work for files in subfolders then you can just hard code it in a config file
define('PROJECT_ROOT', 'C:/wamp/www/mysite');
Then when including something you can do;
include PROJECT_ROOT . '/path/to/include.php';
You could alternativly set the base directory in your .htaccess file
SetEnv BASE_PATH C:/wamp/www/mysite/
Then in PHP you can reference it with $_SERVER['BASE_PATH']
Try this:
$_SERVER['DOCUMENT_ROOT']