Trouble defining a variable in PHP? - 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.

Related

Passing Variables To PHP Include (Within Modal) [duplicate]

I'm trying to pass a variable into an include file. My host changed PHP version and now whatever solution I try doesn't work.
I think I've tried every option I could find. I'm sure it's the simplest thing!
The variable needs to be set and evaluated from the calling first file (it's actually $_SERVER['PHP_SELF'], and needs to return the path of that file, not the included second.php).
OPTION ONE
In the first file:
global $variable;
$variable = "apple";
include('second.php');
In the second file:
echo $variable;
OPTION TWO
In the first file:
function passvariable(){
$variable = "apple";
return $variable;
}
passvariable();
OPTION THREE
$variable = "apple";
include "myfile.php?var=$variable"; // and I tried with http: and full site address too.
$variable = $_GET["var"]
echo $variable
None of these work for me. PHP version is 5.2.16.
What am I missing?
Thanks!
You can use the extract() function
Drupal use it, in its theme() function.
Here it is a render function with a $variables argument.
function includeWithVariables($filePath, $variables = array(), $print = true)
{
$output = NULL;
if(file_exists($filePath)){
// Extract the variables to a local namespace
extract($variables);
// Start output buffering
ob_start();
// Include the template file
include $filePath;
// End buffering and return its contents
$output = ob_get_clean();
}
if ($print) {
print $output;
}
return $output;
}
./index.php :
includeWithVariables('header.php', array('title' => 'Header Title'));
./header.php :
<h1><?php echo $title; ?></h1>
Option 3 is impossible - you'd get the rendered output of the .php file, exactly as you would if you hit that url in your browser. If you got raw PHP code instead (as you'd like), then ALL of your site's source code would be exposed, which is generally not a good thing.
Option 2 doesn't make much sense - you'd be hiding the variable in a function, and be subject to PHP's variable scope. You'ld also have to have $var = passvariable() somewhere to get that 'inside' variable to the 'outside', and you're back to square one.
option 1 is the most practical. include() will basically slurp in the specified file and execute it right there, as if the code in the file was literally part of the parent page. It does look like a global variable, which most people here frown on, but by PHP's parsing semantics, these two are identical:
$x = 'foo';
include('bar.php');
and
$x = 'foo';
// contents of bar.php pasted here
Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you're not redirecting to second.php you're just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:
vars.php
<?php
$color = 'green';
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
Considering that option number one is the closest to this example (even though more complicated then it should be) and it's not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).
I have the same problem here, you may use the $GLOBALS array.
$GLOBALS["variable"] = "123";
include ("my.php");
It should also run doing this:
$myvar = "123";
include ("my.php");
....
echo $GLOBALS["myvar"];
Have a nice day.
I've run into this issue where I had a file that sets variables based on the GET parameters. And that file could not updated because it worked correctly on another part of a large content management system. Yet I wanted to run that code via an include file without the parameters actually being in the URL string. The simple solution is you can set the GET variables in first file as you would any other variable.
Instead of:
include "myfile.php?var=apple";
It would be:
$_GET['var'] = 'apple';
include "myfile.php";
OPTION 1 worked for me, in PHP 7, and for sure it does in PHP 5 too. And the global scope declaration is not necessary for the included file for variables access, the included - or "required" - files are part of the script, only be sure you make the "include" AFTER the variable declaration. Maybe you have some misconfiguration with variables global scope in your PHP.ini?
Try in first file:
<?php
$myvariable="from first file";
include ("./mysecondfile.php"); // in same folder as first file LOLL
?>
mysecondfile.php
<?php
echo "this is my variable ". $myvariable;
?>
It should work... if it doesn't just try to reinstall PHP.
In regards to the OP's question, specifically "The variable needs to be set and evaluated from the calling first file (it's actually '$_SERVER['PHP_SELF']', and needs to return the path of that file, not the included second.php)."
This will tell you what file included the file. Place this in the included file.
$includer = debug_backtrace();
echo $includer[0]['file'];
I know this is an old question, but stumbled upon it now and saw nobody mentioned this. so writing it.
The Option one if tweaked like this, it should also work.
The Original
Option One
In the first file:
global $variable;
$variable = "apple";
include('second.php');
In the second file:
echo $variable;
TWEAK
In the first file:
$variable = "apple";
include('second.php');
In the second file:
global $variable;
echo $variable;
According to php docs (see $_SERVER) $_SERVER['PHP_SELF'] is the "filename of the currently executing script".
The INCLUDE statement "includes and evaluates the specified" file and "the code it contains inherits the variable scope of the line on which the include occurs" (see INCLUDE).
I believe $_SERVER['PHP_SELF'] will return the filename of the 1st file, even when used by code in the 'second.php'.
I tested this with the following code and it works as expected ($phpSelf is the name of the first file).
// In the first.php file
// get the value of $_SERVER['PHP_SELF'] for the 1st file
$phpSelf = $_SERVER['PHP_SELF'];
// include the second file
// This slurps in the contents of second.php
include_once('second.php');
// execute $phpSelf = $_SERVER['PHP_SELF']; in the secod.php file
// echo the value of $_SERVER['PHP_SELF'] of fist file
echo $phpSelf; // This echos the name of the First.php file.
An alternative to using $GLOBALS is to store the variable value in $_SESSION before the include, then read it in the included file. Like $GLOBALS, $_SESSION is available from everywhere in the script.
Pass a variable to the include file by setting a $_SESSION variable
e.g.
$_SESSION['status'] = 1;
include 'includefile.php';
// then in the include file read the $_SESSION variable
$status = $_SESSION['status'];
You can execute all in "second.php" adding variable with jQuery
<div id="first"></div>
<script>
$("#first").load("second.php?a=<?=$var?>")
</scrpt>
I found that the include parameter needs to be the entire file path, not a relative path or partial path for this to work.
This worked for me: To wrap the contents of the second file into a function, as follows:
firstFile.php
<?php
include("secondFile.php");
echoFunction("message");
secondFile.php
<?php
function echoFunction($variable)
{
echo $variable;
}
Do this:
$checksum = "my value";
header("Location: recordupdated.php?checksum=$checksum");

Is it possible to include file in an include file in 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!

Can't understand why a simple if-else statement is not printing words in html title tag

I am new to php, and can't figure out what to search for to describe this problem:
I have a page and it has:
$metatitle = "My page title";
In the header file that is being included:
if($metatitle == ''){
$metatitle = "Some generic title";
}
and...
<title><?php echo $metatitle;?></title>
Now, the page is showing the "Some generic title" so I know it's working somewhat, but it's ignoring the fact that I have indeed put some text in that page.
PHP Version 5.2.17
SOLVED: Thanks for the speedy answers though! I got it working by adding an else statement:
else {
$metatitle;
}
BTW, this was someone else code--pretty bad mistake coming from an actual programmer
P.S. Had to edit the question cause stackoverflow wouldn't let me answer my own question so soon.
You probably have them out of order. If you include the header file, and then declare the variable $metatitle, it's running the if block and printing out the title tags before it ever gets down to the variable. Place the variable declaration before the include(header.php) statement, like so:
$metatitle = "Current page";
include_once("includes/header.php");
If your if condition is inside a function or if the echo is inside a function then you need to declare
global $metatitle;
inside the function.

How to allow only specific pages to be included

Yesterday I asked a question about how to include files passed in via the URL, and someone give me this:
if (isset($_GET['file'])){
include($_GET['file'].'.php');
}
But one of the answers told me to do something with this to avoid possible attacks from hackers or something like that. The problem is that I don't understand how to do it myself.
He said I should do something like this:
$pages_array=('home','services','contact').
And then check the GET var:
if(!in_array($_GET['page'], $pages_array) { die(); }
What does this do, and how do I integrate it into my original code above?
Your original code is looking for a file parameter in the URL, and then including whatever file was passed in. So if somebody goes to your PHP page and adds ?file=something.txt to the URL, you'll include the contents of something.txt in your output.
The problem with this is that anybody can manually modify the URL to try to include whatever file they want - letting them see files on your system that should be private.
The solution is to have a list of allowed filenames, like this:
$pages = array('home', 'services', 'contact');
And then before you include the file, check that it's one of the allowed filenames first.
$pages = array('home', 'services', 'contact');
if (isset($_GET['file'])){
if (!in_array($_GET['file'], $pages_array)) {
exit('Not permitted to view this page');
}
include($_GET['file'].'.php');
}
We're using a PHP array to define the list of allowed pages, checking if our page is in the list with the in_array() function, and then stopping all script execution if it's not in the list with the exit() function.
The code checks the GET information passed from the browser to your PHP page by making sure that the page name is present in your $pages_array.
As long as you list all of the pages in your $pages_array, the code will execute. If the page is not in your array list, then it will die and not be executed.
When using GET it is always beneficial to validate the code sent in this way, as arbitrary statements can be sent and executed without validation.
The code, in this instance, is being validated - so you have taken the necessary steps; as long as there is nothing more to the code that you haven't submitted.
Correct code
$pages_array=array('home','services','contact');
You almost answered your own question...
Except this line becomes...
$pages_array=array('home','services','contact');
Instead of what you had...
$pages_array=('home','services','contact').
//change the variable array declaration
$newArray = array('home','services','contact');
Just do an else statement in your if like
else {
//include your file
include($_GET['page'].'.php');
}
Basically, Your syntax for an array definition is wrong, but also why die() if $_GET['file'] is not set? would it not be better if you reverted to a default so as to fail silently.
Using in_array()
<?php
$pages_array = array('home','services','contact');
if(isset($_GET['file']) && in_array($_GET['file'], $pages_array)){
include($_GET['file'].'.php');
}else{
include('home.php');
}
?>
Or even using switch() with hard coded values.
<?php
$page = isset($_GET['file']) ? $_GET['file'] : 'home';
switch($page){
case "home" : include($page.'.php'); break;
case "services" : include($page.'.php'); break;
case "contact" : include($page.'.php'); break;
default:
include('home.php');
break;
}
?>
$pages=array('home','services','contact');
if(isset($_GET['page']))
{
$page=$_GET['page'];
if(!in_array($page,$pages))
{
die ('');
}
else {
include($page.'.php');
}
}
So, your links will look like:
yoursite.com/index.php?page=home -> with this tool:
http://www.generateit.net/mod-rewrite/
you can make nicer URL's.

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