Change of folder path when require/ include an php file - php

I am currently using an index.php to include another file , it structure like:
root / index.php
/ new/ index.php
/ img/ test.jpg
And I write following in root/index.php :
<?php
require_once("new/index.php");
?>
the problem is , all paths in it are wrong. As all paths are based on new/index.php.
For example, In new/index.php my test.jpg is like
<img src="img/test.jpg" />
It shows http://www.test.com/new/img/test.jpg when I directly access new/index.php
But it shows http://www.test.com/img/test.jpg when I include the php in index.php.
How to fix it? I tried chdir() but it does not work expect Thanks

Make sure you always include with an absolute path, like:
require_once(dirname(__FILE__) . "/otherfile.php");
require_once(dirname(__FILE__) . "/../uponefolder.php");
require_once(dirname(__FILE__) . "/sub/folder/file.php");
Or use autoloading.

Did you just ask the same question twice? Use the required / included file as base directory in PHP
See my answer there.

The folder path you have in the require_once() function is relative to the directory your page is currently in. Have a look at the set_include_path function. Specifically, you could add that function to the top of your scripts to set the root include folder. Something like this:
set_include_path("/var/www/html/root");
require_once("new/index.php");

You could simply change the included HTML document base by adding a base tag.
https://developer.mozilla.org/fr/docs/Web/HTML/Element/base
<head>
<base href="your_new_url_base" target="_blank">
</head>
The HTML included file could check "Am I included from a parent?" if so "I have to change my base tag"...
// new/index.php
echo '<head>';
if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) {
// called directly, no need base tag;
} else {
// included/required
echo '<base href="your_new_url_base" target="_blank">';
}
echo '</head>';

Related

Add Header, Footer and navbar files on multiple pages

Let says below are my web directories:
From web searching i get to use include or require_once and something similar.But I'm confuse in different directory causes much of directory error.
And my question is, how to include Navbar or Footer or Specific Pages in different directory.
Condition: Same directory as above;
For header,navBar and footer you should used simple
include(page/header.php);
About require and include function Reference
The require() function is identical to include(), except that it
handles errors differently. If an error occurs, the include() function
generates a warning, but the script will continue execution. The
require() generates a fatal error, and the script will stop.
But for image,css files and other js files you should follow these steps
Create config.php file
add this in config.php
define('BASE_URL', 'http://your_website_url');//OR define('BASE_URL', 'localhost')
you can use this path like
<?php
include('config.php');//add this code into top of the page
?>
and finally you can used where you want, like
For Style sheet
<link rel="stylesheet" href="<?php echo BASE_URL; ?>/css/styles.css" />
Create a config.php file in your home directory.
<?php
/* Saves the directory path to base directory as `BASE_DIR`
Example: /var/user1/home/public_html/
'Base directory' is where your homepage/index.php is located */
define('BASE_DIR', dirname(__FILE__) . '/');
?>
now just require this config.php file
<?php
require_once('config.php'); //add this line at top of your pages
// No need to include this inside 'header.php' and 'footer.php'
?>
Now u can include files easily, use it in index.php as follows:
<?php
require_once('config.php');
require(BASE_DIR . 'query/conn.php');
// becomes '/var/user1/home/public_html/query/conn.php'
include(BASE_DIR . 'pages/header.php');
include(BASE_DIR . 'pages/navbar.php');
include(BASE_DIR . 'pages/footer.php');
?>
Note: Similar approach is used by WordPress (learn more)

PHP include paths within directories

I have looked around at a few different questions about the same sort of problem I'm having. I have took a solution and adapted it to my own project.
Here is my directory structure.
/css
-style.css
/includes
-shop.css
-header.php
-footer.php
/php
/js
/shop
-index.php
-index.php <-- homepage
-config.php
Inside my config.php I have
define('ROOT_PATH',$_SERVER['DOCUMENT_ROOT']);
My header.php
<?php include './config.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<?php echo '<link href="'.ROOT_PATH.'/css/style.css" rel="stylesheet">';?>
<?php if ($_SERVER['REQUEST_URI'] == '/shop/'){echo '<link href="'.ROOT_PATH.'/includes/shop.css" rel="stylesheet">';} ?>
</head>
The only problem is, for any other page other than the root index.php file, the path for the config.php file becomes incorrect. Thus the CSS paths then become incorrect as ROOT_PATH isn't defined anywhere.
What would be the best way to handle paths when using includes?
Use $_SERVER['HTTP_HOST'].$_SERVER['DOCUMENT_ROOT'] gets the document root for eg var/com/images. $_SERVER['HTTP_HOST'] will get current url like http://example.com/images.TYour code should look like this
define('ROOT_PATH',$_SERVER['HTTP_HOST']);
And include this way
<?php include'../config.php';
Hope this helps you
Maybe using relative paths for the include in the other index.php file.
<?php include '../config.php'; ?>
You are using the server's actual filesystem path to refer to your stylesheets. That's like trying to do something like:
<link href="C:\your_website_path/includes/shop.css"...
and wont work.
I would recommend to change that to something like:
define('ROOT_PATH', 'http://www.your-website-url.com/');
Regards,
what you need to do is make the include for your config absolute, not relative. you begin the path with a dot ./config which means its relative. instead set up your header to include the config file with an absolute path like this
<?php include '/home/user/config.php';?>
This way, any page can find the file no matter its location in the directory structure.

PHP include absolute path

I have a variable on my site called $basePath which is set as:
$basePath = '/Systems/dgw/';
I am using it on all my css, js and images tags as so (shortened for better visibility):
<link href="<?php echo $basePath; ?>include/assets/css/bootstrap.min.css">
I have no problem with those includes and they work fine in wherever file and in whatever folder I am.
I have a certain included page which has the following line:
<img src="<?php echo $basePath; ?>images/new_logo.png" alt="logo"/>
And the image shows just fine. The line after it states:
<?php include($basePath.'include/assets/common/topMessages.php');?>
But the include doesn't happens. When I try it like this:
<?php include('../../include/assets/common/topMessages.php');?>
It works.
Anybody has any idea what could be wrong?
You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/yourpath/yourfile.php";
include_once($path);
?>
If your server doesn't populate the "document_root", you may need this
require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");
I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.
For example, let's say i have this file tree:
domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php
I can include the functions.php file from wherever i am, just by copy pasting
require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");
If you need to use this code many times, you may create a function that returns the "str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))" part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named "path_back"):
require(path_back()."/_resources/another_php_file.php");
You can add an include_path = ".:/home/myuser/mysite.com/" to your php.ini or you can add something like this into your script before the include or require:
set_include_path(get_include_path() . ":/home/myuser/mysite.com/");
The first one will work for all the scripts running in your website.
The second option will only work for the script which has the setincludepath on the code, for the rest of the application it will not work unless you have an object you call in every script that add the setincludepath.

how to include another php file?

I have a php file, and I want to include another php file that have css link tags and javascript source tags, but when I try to include them, it doesn't get added to the page.
my php page:
<?php
$root = $_SERVER['SERVER_NAME'] . '/mysite';
$theme = $root . '/includes/php/common.php';
echo $theme;
include($theme);
?>
common.php:
<link rel='stylesheet' type='text/css' href='../css/main.css'/>";
Anyone know whats wrong? Thanks
PHP's include is server-side, so you need to use the server side path. It is better to use dirname(__FILE__) instead of $_SERVER['SSCRIPT_NAME'], but $_SERVER['SERVER_NAME'] is absolutely wrong.
Try:
include dirname(__FILE__)."/common.php";
Or if the file you want to include is not on the same directory, change the path. For example for a parent directory, use dirname(__FILE__)."/../common.php".
Note that some might suggest using include "./common.php" or similar. This could work, but will most likely fail when the script invoking include is actually being included by another script in another directory. Using dirname(__FILE__)."/common.php" will eliminate this problem.
Change your code to this:
<?php
$theme = 'includes/php/common.php';
echo $theme;
include($theme);
?>
If your includes folder is in the same folder as your php page then it should work, if not add you domain name instead. SERVER_NAME is not needed in this instance.

php: setting root directory for project?

i'm having the following url for my test project on my local server:
http://localhost/projects/test/
now i'd like to have to have the possibilty of using this as root directory for eg. includes/images - like <img src='/img/test.jpg'> - this way it would save me a lot of time as i could simple put it online without any path modifications/flag.
any ideas how this could work?
thanks
I guess this is not a PHP related question, but more on HTML. You may look on the <base> Tag. So instead of saying:
<img src='/img/test.jpg'>
go and make:
<head><base href="http://localhost/projects/test/" /> ... </head>
<body>
<img src="img/test.jpg" />
</body>
Which will in fact point to: http://localhost/projects/test/img/test.jpg
and for the PHP scripts use the set_include_path() function
<?php
$path = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>
I'm not sure what you are asking, but any image links that do not begin with a forward slash / will be local to the document's path.
So for the document http://localhost/projects/test/test.html
The tag <img src='img/test.jpg'> will point tohttp://localhost/projects/test/img/test.jpg`
If you're using relative paths and assuming that /img/ is a subdirectory of /test/, no change is necessary.
If you want to use absolute paths, you can define a constant somewhere(config.php maybe) with the website root and then reference things like this:
<?php echo "<img src = '" . $root . "/img/test.jpg'>"; ?>
If you're including something you can try to use set_include_path and include_path
http://www.php.net/manual/en/ini.core.php#ini.include-path

Categories