Is it possible to include file in an include file in PHP - php

I have a basic page structure in php that contains include files for head and footer.
In the footer, i want to add an include file that will load only if the page as the data-table class.
Something like:
if ($class == 'data-table')
include(SHARED_PATH . '/load-datatables.php');
My goal is to load scripts only when needed. I'm a newby in PHP so I want to start with simple things.
Thanks!

If you are going to search for the "data-table" class in the page using php that would be hard. Although here's what you can do.
Add a php variable that indicates whether the datatable class "data-table" is being used in the page
// index.php
<?php $pageUsesDataTable = true; ?>
...
...
<table class="data-table">.....</table>
// Then load the script if depending on the variable
if ($pageUsesDataTable)
include(SHARED_PATH . '/load-datatables.php');
Or you could just check if the "data-table" class exists in the page, if so initialize the datatable if it is generic
// dTable.js or <script>
if($('.data-table').length != 0) {
// initialize the datatable
}
Although there's always a cleaner approach out there, try to search deeper. Good luck

Put this variable in those pages where you want to include the php-file load-datatables:
$include_datatables_file = true;
Then include a generic file called checkinclude.php on all your pages:
checkinclude.php:
if (!isset($include_datatable_file)) {$include_datatable_file = false;}
if ($include_datatable_file === true) {
include_once(SHARED_PATH . '/load-datatables.php');
}

After Anurag's comment: Did you try it... Of course I did, but I didn't get the right path so it didn't work. Changed the path and it works as expected.
Like I said, it might not be the cleanest way or the best practice. But it works and it's easy to set up. Thanks for all answers!

Related

Trouble defining a variable in PHP?

Alright, so a content page uses this:
$tab = "Friends";
$title = "User Profile";
include '(the header file, with nav)';
And the header page has the code:
if ($tab == "Friends") {
echo '<li id="current">';
} else {
echo '<li>';
}
The problem is, that the if $tab == Friends condition is never activated, and no other variables are carried from the the content page, to the header page.
Does anyone know what I'm doing wrong?
Update:
Alright, the problem seemed to disappear when I used ../scripts/filename.php, and only occurred when I used a full URL?
Any ideas why?
When you include a full URL, you're not including the PHP script -- you're including the HTML it generates. It's just like you went to http://wherever.your.url.goes, but it's done by the server instead of the browser. The script runs in a whole separate process, caused by a separate request from the server to itself, and none of the $variables are shared between the two.
Short version: When you include http://wherever.your.url.goes, $tab will always be blank. If you include the actual file name, the variable will be shared.
Your code as posted should work. How are you actually including that file? Does that happen inside a function? Then you need to use the global statement for it to work. Example:
File 1:
function my_include($file) {
global $tab; // <-- add this
include '/some/path/' . $file;
}
$tab = 'Friends';
my_inlcude('file_2.php');
File 2:
if ($tab == 'Friends') { ... }
Now you see why it's awful practice to post some stubs and skeches instead of the real code
Try to think, Your question is not a rocket science. Include is like copy-pasting code in place of include operator. Go load your inclided URL in browser, copy resulting code and paste it into your first file and see.

Check referrer?

I am having a problem. I have this code:
$theUrl = $_GET["url"];
include("$theUrl.php");
This gets the url, for example: http://mywebsite.com/index.php?url=test
But what if someone puts in:
http://mywebsite.com/index.php?url=http://theirwebsite.com/someEvilscript
How to avoid this? I want only scripts that i have on my server to be executed and not from other websites. Thanks for help.
One of the good way to handle this is to define a white list of file that can be included. If anything isn't in that list, it should be considered evil and never included.
For example :
<?php
$allowed = array('file1', 'file2', 'file3');
if (in_array($_GET["url"], $allowed)) {
// You can include
} else {
// Error message and dont include
}
?>
Note : As suggested in the comment, the allowed list can be populated dynamically by scanning allowed directory.
You really shouldn't have any code that looks like that. And I mean really. What are you trying to achieve with this? I'm sure there's another way to the same without the risks (and let's say general uglyness).
Like HoLyVieR suggests, whitelisting what can be included is the key to making your current code safe.
Why don't you just create test.php on your site, and use http://mywebsite.com/test.php in the link? This way you can include your initialization script in test.php (and in the other scripts) if needed.

php load page page into div ,java script not working

i am using ajax to load pages into a div
the page is loading fine
but i cant run the php and javascript
in that loaded page
in server i am loading the page like this
file_get_contents('../' . $PAGE_URL);
in the browser i am setting the content of the div
using
eval("var r = " + response.responseText);
and setting the innerHTML for that div
with the retrieve information
but when i get the new inner page
no php or java script is working
is that suppose to be like that ?
Well the php is not going to work I think because the way you are handling it, it is just text. I would suggest using something like include('../' . $PAGE_URL); and that should parse the php.
The javascript problem probably has to do with the fact that you are loading <html> <body> <head> tags in a div I'm not sure what happens when you do that, but it shouldn't work properly. Try using some type of <frame> tag.
In order for your javascript to be executed properly, you have to wait until the browser has finished to load the page.
This event is named onload(). Your code should be executed on this event.
<?php
$file = false;
if(isset($_GET['load'] && is_string($_GET['load'])) {
$tmp = stripclashes($_GET['load']);
$tmp = str_replace(".","",$tmp);
$file = $tmp . '.php';
}
if($file != false && file_exists($file) && is_readable($file)) {
require_once $file;
}
?>
called via file.php?load=test
That process the PHP file, and as long as you spit out HTML from the file simply
target = document.getElementById('page');
target.innerHTML = response.responseText;
Now, i'm fairly certain parts of that are insecure, you could have a whitelist of allowable requires. It should ideally be looking in a specific directory for the files also. I'm honestly not all too sure about directly dumping the responseText back into a DIV either, security wise as it's ripe for XSS. But it's the end of the day and I haven't looked up anything on that one. Be aware, without any kind of checking on this, you could have a user being directed to a third party site using file_get_contents, which would be a Very Bad Thing. You could eval in PHP a file_get_contents request, which... is well, Very Very Bad. For example try
<?php
echo file_get_contents("http://www.google.com");
?>
But I fear I must ask here, why are you doing it this way? This seems a very roundabout way to achieve a Hyperlink.
Is this AJAX for AJAXs sake?

PHP macro / inline functions (to avoid variables to go out of scope)

I have the following dilemma. I have a complex CMS, and this CMS is to be themed by a graphic designer. The templates are plain HTML, with several nested inclusions. I'd like to make it easier for the designer to locate the file to be modified, by looking at the HTML of the page.
What I thought in the first place was to build something stupid like this:
function customInclude($what) {
print("<!-- Including $what -->");
include($what);
print("<!-- End of $what -->");
}
but, guess what? Variables obviously come out of scope in the included file :-) I can't declare them as global or as parameters, as I don't know how they are called and how many are there.
Is there any possibility to implement some kind of "macro expansion" in PHP? An alternative way to call it: I'd like to modify each call of the modify function, in an aspect-oriented style.
I have thought about eval(), is it the only way? Will it have a big impact on performance?
I know this is an old question, but I stumbled upon it and it reminds me of something I used to do it too.
how about if you create the function using a very weird variable?
<?php
function customInclude($___what___) {
echo '<!-- Including '.$___what___.' -->';
include($what);
echo '<!-- End of '.$___what___.' -->';
}
?>
I usually suggest to add a possible variable to display those tags only when necessary, you do not want other people to know...
<?php
function __printIncludeInfo($info, $dump = false){
//print only if the URL contains the parameter ?pii
//You can modify it to print only if coming from a certain IP
if(isset($_GET['pii'])){
if($dump){
var_dump($info);
} else {
echo $info;
}
}
}
function customInclude($___what___) {
__printIncludeInfo('<!-- Including '.$___what___.' -->');
include($what);
__printIncludeInfo('<!-- End of '.$___what___.' -->');
}
?>
in this way you can use the function to print any other information that you need
Not sure if I entirely understand the question, but if you're just trying to make life easier for the designer by showing them the underlying filename of the included file, then you can probably just use this within the template files:
echo '<!-- Start of '.__FILE__.' -->';
....content...
echo '<!-- End of '.__FILE__.' -->';
__FILE__ is just one of several Magic Constants.
Also there's the get_included_files() function that returns an array of all the included files, which might be of use (you could output a list of all the included files with 'tpl' in their name for example).
This is my 100% harcoded solution to custom include problem. It's about using a global var to point the next include filename and then include my custom proxy-include-file (wich replace your custom proxy-include-function)
1 - Add this code to a global include (wherever your customInclude function is defined)
$GLOBALS['next_include'] = "";
$GLOBALS['next_include_is_once'] = false;
function next_include($include_file) {
$GLOBALS['next_include_is_once'] = false;
$GLOBALS['next_include'] = $include_file;
}
function next_include_once($include_file) {
$GLOBALS['next_include_is_once'] = true;
$GLOBALS['next_include'] = $include_file;
}
2 - Create some include proxy-include-file, by example "debug_include.php"
<?php
if(empty($GLOBALS['next_include'])) die("Includes Problem");
// Pre-include code
// ....
if($GLOBALS['next_include_is_once']) {
include_once($GLOBALS['next_include']);
} else {
include($GLOBALS['next_include']);
}
// Post-include code
// ....
$GLOBALS['next_include'] = "";
3 - Perform a search and replace in all your files: (except debug_include.php)
search: 'include((.*));' as a reg.exp
replace with: '{next_include($1);include('debug_include.php');}'
and
search: 'include_once((.*)); as a reg.exp
replace with: '{next_include_once($1);include('debug_include.php');}'
Maybe you should need another search-and-replaces if you have some non-standard includes like
include (.... include (.... include (....
I think you can find some better search-and-replace patterns, but I'm not a regular expression user so I did it the hard way.
You should definitely use objects, namespaces and MVC model. Otherwise there is no pure and clean solution to your problem. And please, don't use eval, it's evil.

How do I use PHP to display one html page or another?

I wanted to use PHP and the if statement, and I wanted to do
if ($variable){
display html page1
}
else {
display html page2
}
How do I do this? An please note, that I do not want to redirect the user to a different page.
--EDIT--
I would have no problem doing that with one of them, but the other file, it would be too much of a hassle to do that.
--EDIT--
Here is the coding so far:
<?PHP
include 'uc.php';
if ($UCdisplay) {
include("under_construction.php");
}
else {
include("index.html");
}
?>
My problem is that it would be really complicated and confusing if I were to have to create an html page for every php page, so I need some way to show the full html page instead of using include("index.html")
if ($variable){
include("file1.html");
}
else {
include("file2.html");
}
The easiest way would be to have your HTML in two separate files and use include():
if ($variable) {
include('page1.html');
}
else {
include('page2.html');
}
using the ternary operator:
include(($variable ? 'page1' : 'page2').'.html');
If you want to avoid creating "an html page for every php page", then you could do something like this, with the "real" content directly inside the PHP page.
<?PHP
include 'uc.php';
if ($UCdisplay) {
include("under_construction.php");
exit;
}
?>
<html>
<!-- Your real content goes here -->
</html>
The idea is this: If $UCdisplay is true, then your under construction page is shown, and execution stops at exit; - nothing else is shown. Otherwise, program flow "falls through" and the rest of the page is output. You'll have one PHP file for each page of content.
You could side-step this issue by moving the code that checks $UCdisplay directly into uc.php; this would prevent you from having to write that same if statement at the top of every file. The trick is to have the code exit after you include the construction page.
For those still looking:
See the readfile(); function in php. It reads and prints a file all in one function.
Definition
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
Reads a file and writes it to the output buffer.

Categories