I need to use file_get_contents() to get the content of a html page (content.html) in a file (file.php) that is in a directory like this:
/content
- content.html
/functions
- file.php
So I tried to use file_get_contents('../content/content.html') to get the html content, but i get this error:
failed to open stream: No such file or directory
I think I might be using the path wrong. What can I do?
Use $_SERVER['DOCUMENT_ROOT'] all the time, so you won't have to deal problematically with the file paths.
Try:
file_get_contents($_SERVER['DOCUMENT_ROOT'] .'/content/content.html');
I think it's better to use __DIR__ here instead on relying on a variable set by the web server :
file_get_contents(__DIR__ . '/../content/content.html')
$_SERVER['DOCUMENT_ROOT'] is error prone as it relies on the webserver (Apache in this case), if you use Nginx instead your code may break as you have to configure it to set this variable...., instead I prefer relying on __DIR__ which is provided by PHP thus environment agnostic.
Related
I need to set these anchor href tags to absolute paths because when I have html docs in folders, the header where I include a lot of stuff doesn't work (need ../ in some cases).
I have looked at a few posts that have suggested using:
$root = realpath($_SERVER['DOCUMENT_ROOT']);
or
$root = "http://" . $_SERVER['SERVER_NAME'];
The first option resulted in an error:
localhost/:1 Not allowed to load local resource: file:///C:/xampp/htdocs/trips/index.php%7D
The second option resulted in this error:
Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\MountainPlanner\includes\header.php on line 17
Warning: include(http://localhost/MountainPlanner/includes/db.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\MountainPlanner\includes\header.php on line 17
Warning: include(): Failed opening 'http://localhost/MountainPlanner/includes/db.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\MountainPlanner\includes\header.php on line 17
I am using XAMPP if that makes a difference.
Thank you!
HREF navbar path != System Path
URL path
It's what you see in your browser address, it's used by HTML (CSS, JavaScript, etc...). PHP don't need to worry about it (except by some streams functions).
To create the base path dynamically, I've used this script
httpProtocol = !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http' : 'https';
$base = $httpProtocol.'://'.$_SERVER['HTTP_HOST'].'/';
And, when put in the href a tag:
Link
System Path
It's what the server use to find any file on the server. PHP uses it to include/require any file located on the server or a shared one. Streams functions could use system path too and URL as well.
As I can see, you're asking about system path. I've used this code to normalize the application path:
ini_set('include_path',
implode(
PATH_SEPARATOR,
array_merge(
array(dirname(__FILE__)),
explode(PATH_SEPARATOR , ini_get('include_path'))
)
)
);
Then, my application root could be used as a absolute path only for my application:
/Application/Require.php
/Application/Script.php
index.php
It'll work on any file as well:
require('Application/Require.php');
require('Application/Script.php');
Set the first line somewhere in your config or constants file or even 1st line in your file.
<?php $base_url = "http://localhost/mysite/"; ?>
Then you can create href links like this:
clickie
$_SERVER contains the headers filled by the web server. It is not reliable and it disables your code from being run in local or testing environments. From php.net:
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the ยป CGI/1.1 specification, so you should be able to expect those.
In summary, do not rely on this to provide information about your server.
PHP provides magic constants __FILE__ and __DIR__ that gives you the full path to the file or directory of the current file.
For PHP includes, you should use these constants with the relative path to the file you wish to access.
For example:
include __DIR__ . '/../file_in_previous_directory.php';
include __DIR__ . '/file_in_same_directory.php';
I'm developing a site on my local wamp stack. I have created an alias to view the site so i go to localhost/eee/ to view it. Ideally i would like to go to www.eee.lo but ever since upgrading to win8 I can't get it to work.
So this is the problem, i'm making modules for the website so i don't have to change all the code etc... And i don't want to have to go around changing all the url's when i migrate to the online server so i'm creating a file called _control.php which has this;
$_SITELOC = "localhost/eee/";
And then each time i want to include a file i will go;
include "$_SITELOC/scripts/inc/_header.php";
But this doesn't work and i can't work out why as if i echo it rather than include it and then i take what it prints and put it into the url it goes to the correct file. But it throws errors on the include, it gives two warnins;
Warning: include(localhost/eee/scripts/inc/_header.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in C:\Users\Chris\Documents\EEE\Website\Site\index.php on line 3
Warning: include() [<a href='function.include'>function.include</a>]: Failed opening 'localhost/eee/scripts/inc/_header.php' for inclusion (include_path='.;C:\php\pear') in C:\Users\Chris\Documents\EEE\Website\Site\index.php on line 3
I read somewhere that it might be to do with the include path so i tried;
set_include_path(get_include_path() . PATH_SEPARATOR . $_SITELOC."/scripts/inc/");
but this too did not work and now i'm not sure where to go.
Thanks, Chris
localhost/eee/ is your public address that you can use in your web browser. This public address should more appropriately be written as http://localhost/eee/. When you move to web server, you get the public address http://www.eee.lo/.
When including files, you have to use file paths. For example, if you have your www (or httpd, whatever) directry in D:\ on windows, then your include path should start with D:\www\eee\.
So, basically you have to use two variables to keep paths.
$_SITELOC = "http://localhost/eee/"; //For all URLs used in your HTML document.
$_INCPATH = "D:\www\eee\\"; //For all internal file includes.
In practice, you will need both of these, and it is good practice to keep the website address and internal paths out of your main script because when uploaded to remote server, not only your public address changes, but you will also have to deal with absolutely different internal (include) paths.
Your idea is basically good, to define one (root) path of the application and include files based on it, but unfortunately you're not doing it quite right. You have basically two ways of doing that.
One way (which I personally find better) is to include local files in your file system, where you can define the root path, i.e. like
define ('ROOT', 'your/document/root/path');
// and then include the files
include ROOT . '/' . '/scripts/inc/_header.php';
The other way would be to include a web resource, what you're trying to do, but you've forgotten to specify the scheme (protocol) you want to use, i.e.
define ('ROOT', 'http://localhost/eee');
// and then include the files
include ROOT . '/' . '/scripts/inc/_header.php';
For more information, see the examples, provided by the documentation for include
Note: If you want to include the source of a php file, i.e. file with definitions of functions, etc., use the first approach. Including files, using the second approach will only include the output produced by that file.
If you include() a URL, you will (probably) be including the output of the script's execution, when you want to include the script's source. It seems like you actually want to include by local file system path.
i'm getting following error in my PHP file.
Warning: include(../config/config.php) [function.include]: failed to open stream: No
such file or directory in C:\xampp\htdocs\my-proj\functions\function.php on line 2
let me describe my folder structure
ROOT folder /index.php
functions / function.php
config / config.php
signup / signup.php
now, If i use absolute path, then it is give the same error in signup.php, and if I use relative path then it is giving this error in index.php
any help would be appreciated.
use
include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
The file paths are relative to the invoked script. If your application gets invoked by http requests to index.php, then the include() path needs to be relative to that - even if the include statement itself is located in the functions.php script.
A common workaround is to make all paths absolute in relation to the document root:
include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
// Note: leaving out array keys only valid in double quote string context.
That would work in index.php and functions.php alike.
Use include __DIR__."/../config/config.php"; if you want to include a file relative to the file you're currently executing in. If you're using a version of php older than 5.3.0 (you shouldn't), replace __DIR__ with dirname(__FILE__).
$_SERVER['DOCUMENT_ROOT'] is not set when using commandline and requires that your project is relative to the DOCUMENT_ROOT instead of allowing the user to place it wherever they please. If phpMyAdmin used this variable, you would be forced to accommodate it instead of just placing it wherever you want. That's another thing, it's a variable, so there's a potential security issue too.
If config.php is necessary, I suggest using require instead, otherwise use if (file_exists($file)) {require $file;} so you can avoid warnings when it doesn't exist and get an error when it can't be read (I assume if it exists, it's intended to be used).
I have a file that is called header (the header of my site).. I use that file in all my site. The problem is that it has this include in it:
include_once("../untitled/sanitize_string.php");
which means that a mistake may be thrown, depending on who calls the header file.
I have directories, subdirectories and subdirectories to the subdirectories.. is there a simple way to prevent this from happening.. Instead of taking the satize string include and placing it on every page and not in the header file
Warning: require_once(/untitled/sanitize_string.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampp\htdocs\PoliticalForum\StoredProcedure\User\headerSite.php on line 7
Fatal error: require_once() [function.require]: Failed opening required '/untitled/sanitize_string.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\PoliticalForum\StoredProcedure\User\headerSite.php on line 7
You may consider setting a global include path while using include.
For php 5.3 you can do:
include_once(__DIR__ . '/../untitled/sanitize_string.php');
where __DIR__ is the directory for the current file
For older versions you can use
include_once(dirname(__FILE__) . '/../untitled/sanitize_string.php');
where __FILE__ is the path for the current file
Lets say you have the following structure:
/app/path/public/header.php
/app/path/public/user/profile.php
/app/path/untitled/sanitize_string.php
If your header.php includes santitize_script.php with a relative path like so:
include_once("../untitled/sanitize_string.php");
the php interpreter will try to include that file RELATIVELY to the current working dir so if you will do a request like http://localhost/header.php it will try to include it from /app/path/public/../untitled/sanitize_string.php and it will work.
But if you will try to do a request like http://localhost/user/profile.php and profile.php includes header.php, than header.php will try to include the file from /app/path/public/user/../untitled/sanitize_string.php and this will not work anymore. (/app/path/public/user beeing the current working dir now)
That's why is a good practice to use absolute paths when including files. When used in header.php, the __DIR__ and __FILE__ constants will always have the same values: /app/path/public and /app/path/public/header.php respectively no matter where header.php will be used thereafter
Use absolute path...
include_once('/home/you/www/include.php');
Use absolute path as yes123 said.
include_once(dirname(__FILE__)."/../untitled/sanitize_string.php");
You're going to have to use absolute paths here, as opposed to relative. I often set up some constants to represent important directories, using the old Server vars. Like so:
define('MY_DIR',$_SERVER['DOCUMENT_ROOT'].'/path/to/yer/dir');
Then, modify your include statement:
include_once(MY_DIR.'/your_file.php');
I'm a total PHP noob and am using a pretty simple PHP include:
<?php include("~head.php"); ?>
to do a bit of templating for a website (to achieve common headers, footers, menus for all my pages).
NOTE: The tilde (~) is simply there to make the directories easier to look at (pushes main files to the top of the list when sorted alphabetically)
It's working great for files that are in the same directory but when I reference a file outside of a directory, like so:
<?php include("../~head.php"); ?>
However, it simply doesn't seem to be finding the file as the header is clearly not being pulled into the markup.
Conversely, if I reference the file with a full url, e.g.
<?php include("http://example.com/~head.php"); ?>
I get the following error code on my page.
Warning: include() [function.include]: URL file-access is disabled in the server configuration in /home/content/65/7392565/html/bikini/angela_bikini.php on line 1
Warning: include(http://example.com/~head.php) [function.include]: failed to open stream: no suitable wrapper could be found in /home/content/65/7392565/html/products/product_a.php on line 1
Warning: include() [function.include]: Failed opening 'http://example.com/~head.php' for inclusion (include_path='.:/usr/local/php5/lib/php') in /home/content/65/7392565/html/products/product_a.php on line 1
Strangely, the "../file.php" syntax works for non-header files (e.g. the include I'm using for the menu).
As such code's gotten to be a bit of a fragmented mess and is difficult to maintain changes across all the different pages. Any thoughts or solutions would be very much appreciated. I really am a noob tho so I probably won't be able to wrap my head around anything too fancy. : )
Thanks for your time.
Jon
Rather than using only the ../ to get the directory above, a construct like this will create the full filepath:
// Assuming you are including from the root
$application_path = dirname(__FILE__);
include("$application_path/../header.php);
Typically I'll do this by defining a constant, rather than using a variable.
define('APP_PATH', dirname(__FILE__));
Use this as:
// Assuming you are including at the file root:
define('APP_PATH', dirname(__FILE__));
include(APP_PATH . "/include/head.php");
// Assuming you are including from /include (one directory in)
// append a "/../" onto the end to indicate that the application
// root is one directory up from the currently executing file.
define('APP_PATH', dirname(__FILE__) . "/../");
include(APP_PATH . "somefile_at_the_root.php");
You have to be careful with the tilde! Under UNIX-like operating systems, the tilde is a shortcut to your home directory. If maybe the Apache server runs under the account www, your file-reference could be interpreted like this:
/home/www/head.php
And for the approach of using the full URL, the error says all:
URL file-access is disabled in the server configuration
Ignoring that it isn't best practice to use full URLs (because your folder structure could change etc.), you have to enable allow_url_include in your php.ini (see PHP.net).
If you really want to have your important files on top, you could use the underscore _.