I have been trying to research what is better to use in order to include repetitive parts of the website - php include function or library(provided in Dreamweaver).
Or maybe there are other - better ways to achieve the same result?
At the moment I use php include and absolute paths. I downloaded the website from the server but it seems that the paths that work on the server don't work on my localhost.
What would be the correct and the best way to write paths in order to make them work on both servers without having to re-write the code?
Thanks
You can call at the start of your script the set_include_path() command and specify relative paths to your libraries
http://www.php.net/set_include_path
Since dream weaver uses library, that's probably wrong ;)
If you want to be sure the code is only included once you might use require_once instead.
Try relative paths instead of absolute
Also an easy way to solve this problem is to define a constant from within the root, normally within your index.php file.
/**Path Environment**/
$root=pathinfo($_SERVER['SCRIPT_FILENAME']);
define ('BASE_FOLDER', basename($root['dirname']));
define ('SITE_ROOT', realpath(dirname(__FILE__)));
define ('SITE_URL', 'http://'.$_SERVER['HTTP_HOST'].'/'.BASE_FOLDER);
Then you can use, SITE_URL and SITE_ROOT throughout your script knowing its the correct path to your web root.
So your old includes look like:
include('/srv/www/somesite.com/public_html/somefile.php');
and your new includes will look like include(SITE_ROOT.'/somefile.php'); then when developing on windows the path will change accordingly.
Put
include_path = ".:/your/absolute/path"
in your php.ini, both Server environment and localhost.
Then you can access the include path file at anywhere of the codes.
Related
This works
<?php include("inc/c.php")?>
But in a folder past this, this does not work
<?php include("../inc/c.php")?>
I have to do
<?php include("/var/web/public_html/etc/inc/c.php")?>
I know in ASP you can enable virtual paths and directories. Is this the same with PHP?
If you're including a file from a folder, all includes are relative to the includer's file.
Therefore, the same code should work for the file in the sub-folder:
<?php include("inc/c.php")?>
You can use realpath(dirname(__FILE__)) to include files relatively to current file:
include(realpath(dirname(__FILE__).'/../inc/c.php'));
You can add directories to PHP's include_path directory. When you specify a relative file name, PHP will look for that file relative to all directories specified in the include_path.
Take a look at http://php.net/manual/en/function.set-include-path.php#example-488.
use
dirname(__file__)
it will return you path of current directory.
But in a folder past this, this does not work
Nope, it does work.
I know in ASP you can enable virtual paths and directories. Is this the same with PHP?
Yes. But whole virtual path thing has nothing to do with your case.
This is not PHP problem. This is developer's problem who is using wrong path.
To make your code fool-proof, always use absolute paths. Build paths not from current location but from the site root. So, it will be all the same in the ANY page on your site.
Most general way would be
include $_SERVER['DOCUMENT_ROOT']."/etc/inc/c.php";
I thought I would ask in case I could do it a better way.
On my local (WAMP) I have all my website in the www folder. ( C:\wamp\www )
Now currently I do this when i include a file:
require_once("".$_SERVER['DOCUMENT_ROOT']."/lib/config.php");
When I am working on local and upload site to a webhost i want to ensure the paths don't breakI
Could someone please tell me if I should be doing it this way?
I want to ensure maximum compatibility; meaning that paths won't break if I, for example, move site from local to whatever web host I decided to use or if I, for example, move from one host to another.
Maybe there is a more bullet proof way of doing it?
The problem with using $_SERVER['DOCUMENT_ROOT'] is that it will break if you move your PHP scripts up or down a directory level. Instead use this:
require_once(dirname(__FILE__) . "/lib/config.php");
__FILE__ is the absolute path of the script. dirname() removes the last path component (the script filename) so you can append other path components to it, like /lib/config.php or /../../lib/config.php or whatever. This will work everywhere.
PHP 5.3 introduced a shorthand for dirname(__FILE__), called __DIR__, but this doesn't work in <5.3.
You should see Include path. For that set_include_path is useful.
What I usually do, is make 1 config file (which might include others) with a few very basic constants:
define('PROJECT_ROOT', dirname(dirname(__FILE__))); // or dirname(__DIR__) for PHP 5.3
define('PROJECT_WEB', $_SERVER['DOCUMENT_ROOT']);
// etc
Al my other files/includes will be based on those very simple constants. I will never need relative paths and never the include_path, because both PROJECT_ROOT and PROJECT_WEB are 'real'/absolute.
Other useful (?) constants would be PROJECT_LOGIC and/or PROJECT_CONTROLLERS and/or PROJECT_3RD_PARTY etc.
That works fine for including the config file (although i would get rid of the beginning quotes)
require_once( $_SERVER['DOCUMENT_ROOT'] . "/lib/config.php" );
This is really the only way to do it if you are including the config file from a bunch of different directories.
On bigger project id say that "most" developers have a front controller that all scripts are loaded from. This front controller loads the config file and since its the same file always including the config file there's no need for $_SERVER['DOCUMENT_ROOT'].
in my config.php where i have all constants i set the PATH to a absolute path.
but this means that when i move my application folder i have to change this path.
i wondered if its better to set a relative path, in that way whenever i move my application between production and development folder, i dont have to change it.
how do you guys do when you move between folders?
The best way I've found is to do the following:
define("PATH", realpath(dirname(__FILE__)));
That gives you the directory of the current file. If you do this in your settings/bootstrap/init file, you'll have it available to your application, and it will work for any file system.
__FILE__ is your friend.
define('BASE_PATH', dirname(realpath(__FILE__)));
This will make your scripts more portable.
Include a file like this
include BASE_PATH . 'includes/header.php';
IMO, absolute paths are bad news. Even if you don't plan to move, your hosting provider could move you, like DreamHost recently did to me. I was fine....
But there are 14 references to "path" on their wiki:
http://wiki.dreamhost.com/Server_Moves
I do three things to solve this:
The first is to use paths relative to the current file and include things using dirname(__FILE__).
The second is to use a loader include that all the pages load. This file has one responsibility: to find the include directory, usually via a relative call. So long as this relative relationship stays, it doesn't need changing.
I also like to support custom settings that belong to the installation rather than the codebase. This is done by an include mechanism and overrides a few settings that will be specific for the server the code is on.
I'm having difficulty with paths in a cms system I'm attempting to build, I've basically got a folder with my header.php and footer.php files inside.
These are included in index.php and work fine. But then when I attempt to use the same includes in a file within my admin sub directory, the images and CSS are broken, obviously because the relative path is now wrong.
So my question is, how can I overcome this?
After reading some of the other questions on here and various other sources, I think absolute paths are the way forward, but I've always used relative paths, so the various concepts of using config files to specify an absolute path are confusing me.
I usually manage to work things out for myself, but it's been a long day and Im stumped!
i usualy have a file called config in my application root and in it i define a constant for base path and a few others:
define('APP_BASE_PATH', dirname(__FILE__));
define('APP_FUNCTIONS_PATH', APP_BASE_PATH . '/functions');
and i include my files like
include (APP_BASE_PATH . 'includes/another_file.php');
include (APP_FUNCTIONS_PATH . '/function_file.php');
that way i can place my aplication in whatever directory, plus i can move files around without to much worries.
also using full path makes the include faster
I prefer setting the environment variables (in Apache, using .htaccess or the .conf). This way you can move all your files freely anywhere in webroot and it will have access to those variables.
SetEnv lib /library/folder/
SetEnv public /my/web/root/
SetEnv environ DEVELOPMENT
Also you can use the variable named 'environ' mentioned in the above .htaccess snippet to include a server specific file as config file in all of your scripts and set various variables there.
require_once getenv('lib')."Configs/Config_".getenv('environ').".php";
Enjoy your freedom!
or...
include($_SERVER['DOCUMENT_ROOT'] .'/includes/header.php');
Relative and absolute paths in PHP are a bit fragile because they depend not just on the current directory of the including file, but also the current working directory.
So you need a two-part solution.
Firstly, you need a redirector. Basically, this is an include file that serves as a single-point-of-call for all other pages. Its job is to go and include the rest of your infrastructure. All your pages call this redirector and only this redirector (but you can chain them).
This redirector now does
include_once dirname(__FILE__).'/include/include.php';
This lets you change your infrastructure's include file, or location and all you have to update is one file. The dirname() call solves all the relative and absolute problems and has it look for the next step relative to itself. And by definition this only changes when you change it, so it will always work.
The second part is a custom includer so you can call content by name with a function and it goes and gets the right file. Burying this in your infrastructure directory is where is goes. It then becomes a black-box that the pages outside this area call without knowing and without needing to know how it works or where it is. That removes the need for path constants to include page fragments because you have one place doing it all for you.
I have had this similar issue and posted this query in this link in SO. The URL is : Issue with PHP include with global path.
While working on the solutions given by people and looking at various threads (including this one - which I had quoted in my solution at the bottom section of my post), I had a way! I had posted the solution as well. It may help some one who is facing a similar issue.
On various pages throughout my PHP web site and in various nested directories I want to include a specific file at a path relative to the root.
What single command can I put on both of these pages...
http://www.example.com/pageone.php
http://www.example.com/somedirectory/pagetwo.php
...to include this page:
http://www.example.com/includes/analytics.php
This does not work:
<?php include('/includes/analytics.php'); ?>
Does it matter that this is hosted in IIS on Windows?
You can just use include $_SERVER['DOCUMENT_ROOT'] . "/includes/analytics.php";
From the perspective of PHP root is the top of the file system on the web server, not the root from the perspective of the web browser.
Most people do one of the below.
Define a constant, in a global configuration file, and use that in each call to require/include.
Or they use code like this.
require_once realpath(dirname(__FILE__).'/config.php');
require_once realpath(dirname(__FILE__).'/lib/Database.php');
Using the environmental variables may be dangerous in some cases and be the source of security issues.
As #Stefan Mai says, PHP doesn't have a "root" path but you can define one quite easily - most sites have a page that's included every time (e.g. configuration file), to which you can add:
define('ROOT', dirname(__FILE__));
Then use include ROOT . '/includes/analytics.php';
Something that's also quite useful is the auto_prepend directive, which you can use in .htaccess on apache - not sure about setting it up on IIS (although you can have a global one in the PHP ini).
If you give include() or require() (or the *_once versions) an absolute pathname, that file will be included. An absolute pathname starts with a "/" on unix, and with a drive letter and colon on Windows.
If you give a relative path (any other path), PHP will search the directories in the configuration value "include_path" in order, until a match is found or there are no more directories to search.
So, in short, to include an absolute filename, give an absolute filename. See also the function realpath().
If you want to set your own include "root", have a look at this question (specifically my answer of course :-)
I combined the above suggestions and came up with this.
In my config.php file, I define ROOT as:
define('ROOT', $_SERVER['DOCUMENT_ROOT']);
Then I use it in my succeding files:
include_once(ROOT."/someFile.php");
include_once(ROOT."/includes/someFile.php");
Use .. to go up a directory. So in pageone.php
include 'includes/analytics.php';
in pagetwo.php
include '../includes/analytics.php';
There's no notion of "root" as you're referring to in PHP as far as I know, though you could define it if you wanted. Best of luck!
This works.
<?php include('c:/inetpub/example.com/includes/analytics.php'); ?>
I'll have to make the c:/inetpub/example.com/ part some kind of global variable so it's somewhat portable from server to server.
The tilde is interpreted as a special character by the shell, so using it inside PHP code won't work regardless of OS.
If you're trying to access something relative to a user home directory you could try getenv() - I'm pretty sure Windows sets an environment variable equivalent to $HOME.
The way I found is:
<?php include $_SERVER['DOCUMENT_ROOT'].'\\Your\\Site\\Path.php' ?>
The \\ is necesary when you have some special character that could be escaped (i.e. \n), so that \\ is \ on the string.
Because you are in windows, you have to use \ instead of /