how to include another php file? - php

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.

Related

Php Include - Subfolders

I'm using php include. Now the files are in the sub-folder.
The error goes exactly like this:
Warning: include(/headertop.php): failed to open stream: No such file or directory in D:\ROLDANKING\xampp\htdocs\mysite\pages\print_design.php on line 11
The HTML/PHP file is this:
<html>
<head>
<title>PRINT DESIGN</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" href="../images/art_favicon.png" type="image/x-icon"/>
<link rel="stylesheet" href="../css/body.css" type="text/css" media="screen"/>
</head>
<?php include ("headertop.php"); ?>
<?php include ("header.php"); ?>
<?php include ("nav.php"); ?>
<body>
<div id="contents">
</div>
</body>
<?php include ("footer.php"); ?>
</html>
Assuming you have the paths correct and files in place you can try this...
<?php
include ("sub-folder/headertop.php");
include ("sub-folder/header.php");
include ("sub-folder/nav.php");
?>
The thing you want to avoid is having to change the path to an include on each page. You can do that with something like this:
<?php include $_SERVER["DOCUMENT_ROOT"] . "/includes/header.php"; ?>
That will work nicely online, but to work in XAMPP, you need to set up a vitrual host so that the link points to the same thing: http://sawmac.com/xampp/virtualhosts/
Warning: include(/headertop.php): failed to open stream: No such file or directory in D:\ROLDANKING\xampp\htdocs\mysite\pages\print_design.php on line 11
says there is NO headertop.php file in your directory
check if the file exists: D:\ROLDANKING\xampp\htdocs\mysite\pages\headertop.php
also you can just use:
<?php
include ("headertop.php");
include ("header.php");
include ("nav.php");
?>
instead of:
<?php include ("headertop.php"); ?>
<?php include ("header.php"); ?>
<?php include ("nav.php"); ?>
<?php include ("SUB_FOLDER/headertop.php"); ?>
try this
include '../headertop.php';
or
include '/headertop.php';
I have come across dozens of webpages over the last 3 days and I think I have collectively tested exactly what most people coming here are looking for.
ABSOLUTE PATHS. They must be manually established on your local host, and then again on your Live website, but this is nothing shy of declaring a variable set to a particular pre-built function.
Stay with me..
Every time I reference a link in a php (includes and echos), or in html and css, I reference a variable set to the root directory + that original link.
e.g.
background-image: url(<?php echo $root; ?>images/bg-0.jpg);
The only downside to this is the visibility of extra code and tediousness of adding a $variable to each and every link in a css or php document. And lord forbid javascript, because I havent even touched the root of that. Heh. Puns.
Anyways, to make this work..
In my Styles.css Doc, I simply convert it to Styles.php, encase the CSS code in
<style type="text/css"> *CSS* </style>
tags, which enable the echo of a PHP variable but as a string, or in our case an absolute path precursor.
In my header file, I now include my CSS as a PHP include with a new Root Variable.
include $php_root.'includes/css/styles.php';
Notice how this $variable is different than the echo's? The way I declared the variables plays a huge role in how CSS/HTML perceives a root destination, and how PHP sees it.
So these were my set variables.
// WAMP Localhost
$root = "http://localhost/PZD/";
$php_root = $_SERVER['DOCUMENT_ROOT'] . "PZD/";
// Live Server
$root = "http://prozechdesigns.com/";
$php_root = $_SERVER['DOCUMENT_ROOT'];
These may be set in your main header.php include itself.
Or if you're like me with database files to connect to and communicate with, you might pair it with a database connect.php file. I did; that way, when I call upon my init.php file or need to edit the init.php, I do not need to worry about which $root variables are being used after overwrite between localhost and live website.
You may not be using WAMP as you're reading this, and at your time and date or configuration, your PHP Root location may not be set like mine is. But if you are using WAMP and perhaps wish to find out where your root is set or change it, look for the httpd.conf file located by default in "wamp/bin/apache/apache#/conf".

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.

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

Change of folder path when require/ include an php file

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>';

PHP code not linking properly missing code

Here is what I have. I have an index php page sitting on my /root/ folder with the following code:
index.php
require_once("access/$template/head.php");
My functions page has the following configuration for the $template code:
funcs.php
function getTemplateFiles() {
$directory = "models/site-templates/";
$languages = glob($directory . "*");
return $languages;
}
My head php page has the following code:
head.php
<link rel='stylesheet' href='$template/css/style.css'>
My question is what code can I add to my index page that will communicate with my head page, a code before my $template that will include the file location of my php page.
Example 1
$include_dir/$template/css/style.css'>
My question being is how can I include the path of my index page so that my head page will read as html like so?
default, does not work $template/css/style.css
need it like this only for the index page access/$template/css/style.css
Replace your code
<link rel='stylesheet' href='$template/css/style.css'>
Use this
<link rel='stylesheet' href='<?php echo $template; ?>/css/style.css'>
I'm not quite sure whether I understand your problem correctly, but these two methods might help:
$currentDir = dirname(__FILE__);
$currentDir will be the path on your server to the file you're currently in. So if you have a structure like this:
/access/functions/myFunction.php
and you're calling this method from myFunction.php, $currentDir will return '/access/functions'. If the file to be included is in the same directory-path, you can include it like this:
$includePath = $currentDir."/myFile.php";
Another way of determining a target directory is using:
$docRoot = realpath($_SERVER["DOCUMENT_ROOT"]);
$docRoot will be the top-directory of your website (usually something like /usr/www/username/public_html/)
Using this, you always know what your top-directory is and then you can include files like this:
$includePath = $docRoot."/models/site-templates/myTemplate.css";

Categories