PHP include absolute path - php

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.

Related

Relative URL issue

I will have multiple folders/modules to access common files. But accessing them seems to be big deal for me!
I did gone through this link to understand the relative positioning and managed to solve some . But not all. Reference: Relative URL's/paths in php
My folder structure is as below:
Website runs on root folder:
/(index|ajax).php
and then the subfolders:
/css/style.css
/img/*.(jpg|png|gif)
/inc/(header|footer).php
/js/*.js
/registration/(ajax|getsubjects|response|success).php
Now, this is how I included files in the index.php page(this displays correctly, meaning, style,css,js,config all accessible)
<?php
include('inc/header.php');
?>
content here
<?php
include('inc/footer.php');
?>
This index page will have to fetch getsubjects.php, response.php and then finally land in success.php.
The success.php need some styling whereas the previous two were only for processing.
So now in the success.php I access header and footer as below:
include('../inc/header.php');
include('../inc/footer.php');
But this doesn't apply any styling!
inside header.php and footer I include files like this:
<link rel="stylesheet" href="./css/style.css">
<script src="./js/script.js"></script>
How should I include the files here please?
./css/style.css means from current directory and would achieve the same result as css/style.css. The easiest answer is to determine what the base path of your application is and use that. For instance, if your application is running as http://myapp.com, then you could set all your front-end paths to /css/style.css. If your app runs in a subdirectory, such as http://example.com/myapp, then your paths would be /myapp/css/style.css.
This does not apply the same on the PHP side. For them, you should really use document-relative paths. Having a PHP file that you include in multiple places in your app, the contents of which having something like include('../myDoc.php');, can lead to complications as the path isn't based on the included document's path, but rather the including. So using document-relative paths, you get around this include(__DIR__ . '/../myDoc.php');. Just something to consider if your app grows.
Your PHP-includes seem to be correct. But in your HTML you need to change the linking to the CSS and JS Files (maybe even to your images).
You could use absolute paths:
<link rel="stylesheet" href="/css/style.css">
<script src="/js/script.js"></script>
the leading dot makes your paths relative to the HTML-Document, so if they are linked from a document in a subfolder, they point to a wrong location.
Including files with
<?php
include("page1.php")
?>
put the code (or content) from page1 into the caller page.
So you may have to detect from where your pages are called, or try absolute links (beginning by /)
I hope I answer you question correctly.

Managing Links within PHP Includes using htaccess

Thanks for reading!
I am managing a header with links using a PHP include. It is within a folder /includes/header.php.
Here's an example of what header.php looks like:
<nav>
<ul>
<li>Home</li>
<li>Page</li>
</ul>
</nav>
When I add the include to a file within the root directory, like /index.php, I add it like so: <?php include_once("header.php"); ?>. This all works fine, and the links point where they need to.
When I do the same thing but with a file in a subdirectory, for instance a file called /foo/page.php I will add the include like this: <?php include_once("../includes/header.php"); ?> - this way it grabs the file correctly.
My problem is that all of the links in the header.php file aren't going where I want them to. I found some information about using a set environment function in .htaccess, but I don't know what to make of it.
If you have an answer to this problem I'd love to hear it! Thanks!
Start all the links in the header from the root web directory.
Just do;
"/index.html"
"/subdirectory/link.html"
So basically just start all the links with a forward slash, as without it, it will look for the page within its current directory.
You can set the base url in your HTML head.
Store the base url of your application in a config file or database and then use it to build absolute links not relative ones. For example you have a file like config.php:
<?php
$baseUrl = "http://yourdomain/yourapp/";
And in header.php:
<?php include_once("config.php"); ?>
Page
It may seem inconvenient having to edit a file in case you move your application, but this way your links will work in any directory any time, and as your application grows there will be some other things like DB access that also have to be changed if you move your application, and can be stored in the same config file.

Basic PHP: Passing An Array From One PHP file to Another

I am making a website in which I want a column on the left hand side to be a list of links. This column populated with links will be on every single web page of the entire site, and it will be updated with more links quite frequently. So the problem I need to solve is how to make it so that whenever I want to add a new link to my website's "link list", I don't have to manually add it in the HTML code in every single web page.
I know some Java but I'm completely unfamiliar with PHP. I did a bit of research and found the "include" declaration, and kind of slapped together something that does work, but I have no clue whether this is a good idea or not - as in if its bad code/bad style, so could I get some opinions on this please? Is it good code? Or am I going about it the wrong way?
The entire php file that contains the array, title "videos_array.php":
<?php
$videoArr = array(
"<li>Video 1</li>",
"<li>Video 2</li>",
"<li>Video 3</li>");
?>
And the web pages where I want to insert these values into look like this:
<html>
<head>
<!--All the necessary tags-->
</head>
<body>
<!--More Tags-->
<div id="link_column">
<?php include 'videos_array.php';
foreach($videoArr as $val){
echo $val;
}
?>
</div>
</body>
</html>
When referencing a php file with the include declaration, is it a relative path that I should be using, or are absolute and virtual references ok as well?
Thanks in advance for your input
Your $videoArr is used only once, so there is no need to use it in another php file you can just echo after declaring it like,
<?php
$videoArr = array(
"<li>Video 1</li>",
"<li>Video 2</li>",
"<li>Video 3</li>"
);
foreach($videoArr as $val){
echo $val;
}
?>
Even no need to create an array if it is not used just echo it as a string like,
<?php
echo "<li>Video 1</li>",
"<li>Video 2</li>",
"<li>Video 3</li>";
?>
And in your index page use it like,
<div id="link_column">
<?php include 'videos_array.php';?>
</div>
When referencing a php file with the include declaration, is it a relative path that I should be using, or are absolute and virtual references ok as well?
What you're doing is fine however there's some points to be wary of around PHP's include path.
The include path is a FIFO stack of server file-system paths that PHP will use as base directories when resolving paths provided in include and require statements (and probably some other things). The basic include path usually includes . (or the current working directory). This is resolved as the directory containing the first (parent) PHP script executed. This can catch people out once you go a few includes deep.
What I find generally works best is to prefix include paths with the __DIR__ constant. This resolves to the parent directory of the current script.
For example, say you have the following directory structure
foo.php
bar.php
dir/baz.php
To include bar.php from foo.php, you can use
include __DIR__ . '/bar.php';
To include bar.php from dir/baz.php
include __DIR__ . '/../bar.php';
You can also manipulate the include_path configuration. For example (in foo.php)
// add "dir" to the top of the include path stack
set_include_path(implode(PATH_SEPARATOR, [
realpath(__DIR__ . '/dir'),
get_include_path()]));
// now include baz.php
include 'baz.php'; // this works because we added "dir" to the include path

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.

How to use images and php includes across multiple directories?

I am brand new to PHP. I want to use it to include a universal header and footer in an html/jquery site. Currently I am using includes to do this:
<?php include('../includes/footer.php'); ?>
This works fine. Where I encounter a problem is with any images in the header or footer.
An explanation of my file structure:
Root folder: contains index.php and the folders "includes", "img", "php" etc.
php folder: contains gallery.php
includes folder: contains header.php, footer.php
When viewing the index.php all images in the header and footer show properly, but, because they are linked relatively (ex "img/facebook.png"), the do not show in gallery.php. To work they would need a ../ included. But then this would defeat the purpose of a universal header.
Thus I am trying to figure out how to link the images in the includes files in way that is doesn't matter where the php file is located. I have read this thread (which sounds like my problem) but I do not understand any of the answers. I have also read things that suggest $_SERVER['DOCUMENT_ROOT'] .'/folder/';, in conjunction with an echo to display the image. I tried this in my footer.php with this code:
<?php
$path = $_SERVER['DOCUMENT_ROOT'] . '/img/';
$image = ($path . "facebook.png");
echo "<img src=\"$image\" />"; ?>
When I view the page though, I end up with a little torn paper icon instead of my image. I assume this means that the path is incorrect, but I do not know why. facebook.png resides in the img folder. This problem occurs on both index.php and gallery.php.
After this rather long winded explanation (sorry), my mains questions are:
1) How do I get images to show up properly in my includes across multiple directories?
2) If I am going about this in the right way with the echo, what are the possible reasons why it is not working?
Once again, I know nothing about php, so if you could try to make your answers as basic as possible, it would be much appreciated.
Thank you!
Instead of img/facebook.png, add a / before the img/ like this: /img/facebook.png
This says "go to the root, and look for the img folder there. All your images should work fine then. The path of the images are absolute or relative based on the HTML page you're viewing, not which files you use to create it.
Though there's probably not much of reason for a "php" folder - just keep all your pages in the root directory.

Categories