When I use the following PHP code:
$id = $_GET['page']; $page = include ($id.'.php'); echo $page;
The code within the $id.php file is returned, however there is a "1" appended to it, any idea why this is happening?
include() will return boolean TRUE if the file was successfully included. You then echo out that true value, which is printed as a 1.
Of note: never directly use user-provided data ($_GET['page']) in file system operations. It's a hideious security risk. You've at least got .php being appended so it's not quite as large a gaping hole, but still... don't do this.
You shouldn't echo a page like that.
include() is used to import the document onto your current working file.
By using $page = include ($id.'.php');, you are assigning boolean value to $page
This will hold the success status of the include() statement
If the page load successfully, it give true, whose numeric value is 1
If the load was unsuccessfully, it gives false, whose numeric value is 0
However, the way you are using is not entirely incorrect
For example: Create a page Test.php to return a value at the end
$t = "some text";
return $t;
Then you will able to use it to echo
echo include("test.php"); //outputs "some text"
I suggest you tead the documenation for complete guide
because the 1 is the return code of the include(), which you are saving in the $page variable.
The code within $id.php is returned when you do the include(), the only thing your 'echo' is printing is the 1
Yes! When you include, you're just telling PHP to parse the additional file as well. The variable you've set--$page-- just contains the return value of the include() function. Since it's 1, I'd say you included the other file successfully.
On a related note, it's generally (meaning, almost never) a good idea to include an arbitrary file based on un-parsed parameters from a user request. By manipulating the value of page passed to your script, a theoretical attacker could get your machine to execute any PHP file in the system--a dangerous proposition!
Most probably because include will return true or false (0 or 1). Actually you include the page content and then echo $page. This will print "1".
Hope you got it. Don't echo $page at the end. Just use include.
Related
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");
i code the following
<?php
if ($id = mysql_real_escape_string(#$_GET['pid'])
&& $uid = mysql_real_escape_string(#$_GET['file']))
echo include "foo.php";
else
echo include "bar.php";
?>
When I use the include function in conjunction with a function that's designed to output to the page (e.g., or echo include 'foo.php'), it returns the include but with a "1" after the content that has been included.
echo include "foo.php"
should be
include 'foo.php';
Note that this can also happen when using include with shorthand echo:
<?= include 'foo.php'; ?>
This will also print out the return value of 1 when used inside a script. To get rid of this you need to use the regular PHP opening tag like so:
<?php include 'foo.php'; ?>
PHP will now include the contents of the file without printing the return value.
Okey so the answers here are actually not entirely correct; in some sense even misleading.
include takes the contents of the file and places them in context. One of the more common uses is to pass variable scope around, ie. passing scoped variables in your view by including them in the handler and using include on the view. Common, but there are also other uses; you can also return inside a included file.
Say you have a file like this:
<?php return array
(
'some',
'php'
'based'
'configuration',
'file'
); # config
Doing $config = include 'example-config-above.php'; is perfectly fine and you will get the array above in the $config variable.
If you try to include a file that doesn't have a return statement then you will get 1.
Gotcha Time
You might think that include 'example-config-above.php'; is actually searching for the file in the directory where the file calling the include is located, well it is, but it's also searching for the file in various other paths and those other paths have precedence over the local path!
So if you know you had a file like the above with a return inside it, but are getting 1 and potentially something like weird PEAR errors or such, then you've likely done something like this:
// on a lot of server setups this will load a random pear class
include 'system.php'
Since it's loading a file with out a return you will get 1 instead of (in the case of our example) the configuration array we would be expecting.
Easy fix is of course:
include __DIR__.'/system.php'
That is because the include function returns 1 on success. You get, as you say, 'my name is earl1' because the code inside the included file runs first, printing 'my name is earl' and then you local echo runs printing the return value of include() which is 1.
Let the file.txt contain xxx
echo include("file.txt");
This returns,
xxx1
The '1' is the return value of the include function, denoting the success that the file is accessed. Otherwise it returns nothing, in this case parse error is thrown.
echo print "hello";
This too returns,
hello1
Same as above; '1' denoting the success,it's printed.
echo echo "hello";
print echo "hello";
Both the above cases produces an error.
Since the echo function has no return value, hence undefined.
echo echo "hello"; print echo "hello";
(1st) (2nd)
Now the second 'echo' in the both cases produces an undefined.The first 'echo' or 'print' can't take in the hello output with the undefined (produced by the second echo).
A verification:
if((print "hello")==1)
echo "hey!";
output: hellohey! ('echo' in the 2nd line can be a print, it doesn't matter)
Similarly,
if((include ("file.txt"))==1)
echo "hey!";
output: xxxhey!
Other hand,
if((echo "hello")==1)
echo "hey!";
output: an error
In the first two cases the functions (print and include) returned 1, in the third case 'echo' produces no return value (undefined) hence the third case produces an error.
Well... I am using Codeigniter(php frame work). And I encountered the same problem. What I concluded is that when we try to print/echo the include method then it prints 1 on screen and when we just simply write the include command(example given below) it will only do what it is supposed to do.
<?php include('file/path'); ?> // this works fine for me
<?= include('file/path'); ?> // this works fine but prints "1" on screen
Hope my explaination will be helful to someone
= is assigning operator
== is for checking equal to
check for php operators
I have solved it returning nothing at the end of the included file:
$data = include "data-row.php";
return $data;
Inside data-row.php:
<div>etc</div>
...
<?php return; //End of file
I found the selected answer from this thread very helpful.
Solution 1
ob_start();
include dirname( __FILE__ ) . '/my-file.php';
$my_file = ob_get_clean();
You might also find this thread about the ob_start() function very insightful.
Solution 2
Add a return statement in the file that is being included.
E.g my-file.php
<?php
echo "<p>Foo.</p>";
return;
Drawn from the answer provided by #gtamborero.
To help you understand it the way I do now, just take this oversimplification:
There should always be a return statement otherwise include will return 1 on success.
Happy coding!
M5
Use return null in foo.php and bar.php
echo substr(include("foo.php"),1,-1);
as we know, return keyword will RETURN some value and exit current function. Mean, that this one used only inside some functions.
BUT, I saw some php-dev's use return keyword outside functions, even in index.php file (in root of web server). What is that mean???? By the way, maybe it's logical to require some file inside function, but this style isnt mine.
There's not much more to say than what the docs do.
About the common usage of return:
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return will also end the execution of
an eval() statement or script file.
About the less common usage:
If called from the global scope, then execution of the current script
file is ended. If the current script file was included or required,
then control is passed back to the calling file. Furthermore, if the
current script file was included, then the value given to return will
be returned as the value of the include call. If return is called from
within the main script file, then script execution ends. If the
current script file was named by the auto_prepend_file or
auto_append_file configuration options in php.ini, then that script
file's execution is ended.
Its documented somewhere within the manual
// myFile.php
return array( 'foo' => 'bar');
// somewhere else
$config = include 'myFile.php';
echo $config['foo'];
If you use return in the main scope php will leave the file inclusion and use the value as "return value" of the inclusion (include[_once](), require[_once]()).
BUT, I saw some php-dev's use return keyword outside functions, even
in index.php file (in root of web server). What is that mean???
You know the common purpose. But what you are asking is used to prevent code injection in php include files. Take a look at this post which explains it:
Prevent Code Injection in PHP include files
While discussing Coding Standards it was not long ago I argued against
adding ?> at the end of php files. But miqrogroove pointed to me an
interesting aspect why it actually can make sense to have it and an
additional return statement at the end of each file: That one (merely
the return statement) can prevent an attacker to append payload code
to existing PHP files, for example known include files. The
countermeasurement is pretty easy, just add a return statement at the
end of the file. It will end the include “subroutine”:
Example:
/* all the include file's php code */
return;
?>
So i have three files.
FILE 1 includes FILE 2 which includes FILE 3
FILE 1 needs to print VAR 1 which is defined in FILE 3
how would I do that?
Its not echoing out for me
file 1
<?php
if ($_GET["pg"]==false)
echo "<title>Socal Mods</title>";
else
echo $title_name;
?>
file 2
<?php
if ($_GET["pg"]==false)
include("home.php");
else
include("".$_GET["pg"].".php");
?>
file 3
<?php $title_name="<title>Socal Mods</title>" ?>
file 3 is being parsed into file 1 which is the display container, but the %title_name is not echoing
One thing first about how you access the GET variables. You check the value using $_GET["pg"] == false. Note that this expression will fail to do what you expect in a lot situations. In fact, the value will never be directly false. The only way it will equal to false if it is empty or unset (in which case you will also get a compiler warning, which you should avoid). Usually a safer way to check if the value was set is using isset( $_GET["pg"] ).
The next thing I want to address is a security problem you introduce. You use the GET value directly to include a file with that name. If I was a user with malicious intent, I could easily set the pg value to something, you usually wouldn't expect and which break your website in some way. You generally should avoid using data the user entered somehow (request parameters are user data), and make sure to sanitize them first. A good way to do this, when you plan to use the value as a base to which page you want to include, would be to have some kind of whitelist of acceptable/allowed values. Then you can check if the entered data is in that whitelist and if that is the case, include the correct page. Another simple way would be using a switch statement to simply go through all accepted cases.
Now finally, onto your problem: I'm not sure if this was just a mistake when you posted the code, but file 1 is missing the include of file 2. As such you will never include file 3, and of course the variable will never be set.
Another problem might be the usage of the GET value. If the value does not contain the exact filename (as in casing and no extra whitespace), then the file won't be found. It is a good idea to echo out the filename you want to include in file 2, just to check if you are making any mistakes. The whitelist as explained above would be another way to make sure that you are trying to include the correct file.
Finally, you should enable error reporting on your server, you can do that either in your server configuration, or by adding the following line to the top of your first file (i.e. file 1):
error_reporting( E_ALL );
That way you will get errors and warnings that will tell you if something unexpected happened at runtime, and you might see your mistake easier.
Old answer
In general it works like this:
File 1:
<?php
include 'file2.php';
echo $myVariable; // prints 'Hello World!'
?>
File 2:
<?php
include 'file3.php';
?>
File 3:
<?php
$myVariable = 'Hello World!';
?>
echo $title_name = "<title>Socal Mods</title>";
It means its echoing html, So "Socal Mods" will be seen in title bar instead of the body. I hope you are looking in the titlebar. And to use $title_name in file 1 which is available in file 3 you hv to include file3 in file1.
Is file 3 included in the script? And have you actually validated and confirmed that the file is included? If you change the include statements in your script into require statements, PHP will stop with an error if the file you are looking for does not exist.
There are many reasons why a file might not be found. If the file name contains uppercase letters and the request only contains lowercase letters, you will run into problems if the server uses a case sensitive file system.
Also you should sanitize user input before you use that to include files. You don't want me to be able to include any file anywhere on your server, do you?
Variabes have to be created, set and assigned a value before they can be echoed.
Most probably ( please show us some code ), your problem is not the file includes, but you are trying to echo your variable before it is assigned a value.
i code the following
<?php
if ($id = mysql_real_escape_string(#$_GET['pid'])
&& $uid = mysql_real_escape_string(#$_GET['file']))
echo include "foo.php";
else
echo include "bar.php";
?>
When I use the include function in conjunction with a function that's designed to output to the page (e.g., or echo include 'foo.php'), it returns the include but with a "1" after the content that has been included.
echo include "foo.php"
should be
include 'foo.php';
Note that this can also happen when using include with shorthand echo:
<?= include 'foo.php'; ?>
This will also print out the return value of 1 when used inside a script. To get rid of this you need to use the regular PHP opening tag like so:
<?php include 'foo.php'; ?>
PHP will now include the contents of the file without printing the return value.
Okey so the answers here are actually not entirely correct; in some sense even misleading.
include takes the contents of the file and places them in context. One of the more common uses is to pass variable scope around, ie. passing scoped variables in your view by including them in the handler and using include on the view. Common, but there are also other uses; you can also return inside a included file.
Say you have a file like this:
<?php return array
(
'some',
'php'
'based'
'configuration',
'file'
); # config
Doing $config = include 'example-config-above.php'; is perfectly fine and you will get the array above in the $config variable.
If you try to include a file that doesn't have a return statement then you will get 1.
Gotcha Time
You might think that include 'example-config-above.php'; is actually searching for the file in the directory where the file calling the include is located, well it is, but it's also searching for the file in various other paths and those other paths have precedence over the local path!
So if you know you had a file like the above with a return inside it, but are getting 1 and potentially something like weird PEAR errors or such, then you've likely done something like this:
// on a lot of server setups this will load a random pear class
include 'system.php'
Since it's loading a file with out a return you will get 1 instead of (in the case of our example) the configuration array we would be expecting.
Easy fix is of course:
include __DIR__.'/system.php'
That is because the include function returns 1 on success. You get, as you say, 'my name is earl1' because the code inside the included file runs first, printing 'my name is earl' and then you local echo runs printing the return value of include() which is 1.
Let the file.txt contain xxx
echo include("file.txt");
This returns,
xxx1
The '1' is the return value of the include function, denoting the success that the file is accessed. Otherwise it returns nothing, in this case parse error is thrown.
echo print "hello";
This too returns,
hello1
Same as above; '1' denoting the success,it's printed.
echo echo "hello";
print echo "hello";
Both the above cases produces an error.
Since the echo function has no return value, hence undefined.
echo echo "hello"; print echo "hello";
(1st) (2nd)
Now the second 'echo' in the both cases produces an undefined.The first 'echo' or 'print' can't take in the hello output with the undefined (produced by the second echo).
A verification:
if((print "hello")==1)
echo "hey!";
output: hellohey! ('echo' in the 2nd line can be a print, it doesn't matter)
Similarly,
if((include ("file.txt"))==1)
echo "hey!";
output: xxxhey!
Other hand,
if((echo "hello")==1)
echo "hey!";
output: an error
In the first two cases the functions (print and include) returned 1, in the third case 'echo' produces no return value (undefined) hence the third case produces an error.
Well... I am using Codeigniter(php frame work). And I encountered the same problem. What I concluded is that when we try to print/echo the include method then it prints 1 on screen and when we just simply write the include command(example given below) it will only do what it is supposed to do.
<?php include('file/path'); ?> // this works fine for me
<?= include('file/path'); ?> // this works fine but prints "1" on screen
Hope my explaination will be helful to someone
= is assigning operator
== is for checking equal to
check for php operators
I have solved it returning nothing at the end of the included file:
$data = include "data-row.php";
return $data;
Inside data-row.php:
<div>etc</div>
...
<?php return; //End of file
I found the selected answer from this thread very helpful.
Solution 1
ob_start();
include dirname( __FILE__ ) . '/my-file.php';
$my_file = ob_get_clean();
You might also find this thread about the ob_start() function very insightful.
Solution 2
Add a return statement in the file that is being included.
E.g my-file.php
<?php
echo "<p>Foo.</p>";
return;
Drawn from the answer provided by #gtamborero.
To help you understand it the way I do now, just take this oversimplification:
There should always be a return statement otherwise include will return 1 on success.
Happy coding!
M5
Use return null in foo.php and bar.php
echo substr(include("foo.php"),1,-1);