So basically I have a file, lets say file1.php and it includes another file2.php.
file1.php contains a variable called $dateString that I have performed some operations on.
file2.php also has the same variable called $dateString however this variable is not being referenced within this include file even though $dateString was initialized prior to including file2.php.
So this is currently how file1.php looks like:
$dateString = 'some expression';
include 'file2.php';
file2.php is basically trying to echo out the variable that was initialized in file1.php
echo $dateString;
Everything else from file2.php is being called properly except that one variable.
Hopefully this makes sense. Is this possible in PHP? I have read in other places that you need to make the variables global and others have mentioned how you cant reference a variable from a parent file within a child file..any thoughts? Thanks in advance!
there is nothing magically happening when you use PHP's include(). the included file's code is basically just inserted at the point where you are including it - resulting in one bigger PHP file.
it doesn't really matter if the "parent" or in the "child" file - it's the position that matters since PHP will parse the single resulting file from top to bottom.
for example: if you set the variable in file A before including file B, file B will know about the variable. but if you set the variable in file A after including file B - file B doesn't know it.
With coding you should always try and test your own things before asking other people, butch like what #bub suggested in the comments.
Variables are global pretty much, you are able to include another file and use variables that are in file1.php in file2.php.
Otherwise, if you are using them in a function, I'd suggest using:
global $var;
the above should only be used in a function.
Related
I have file a.php with:
define('COLOR','blue');
and file b.php with:
include('/a.php');
echo COLOR;
... and "COLOR" is echoed. Is there something I need to do to carry the definition over?
File B is a WordPress functions file, which is possibly the cause - but I want to check first that the PHP is correct, having never used define() before... Thanks.
This should work just as you expect, however I think you have an issue on your include:
include('/a.php');
The leading slash anchors it to the root directory, which is almost certainly not what you want. I recommend using require instead so that you get an error if it fails:
require('a.php');
I know similar questions have been asked, but unfortunately I didn't manage to solve the problem after going through them.
Assuming this situation: In one.php I'm retrieving some data from an input field and saving it as a variable and later on I require two.php
one.php
$rejon = $_POST['rejon'];
require 'two.php';
two.php
--here I would like to use $rejon ---
When I try to use $rejon in two.php, it doesn't work (I try to insert it into a database to be exact). On the other hand, if I don't require the two.php but instead paste the code into one.php, it works.
I don't understand why this happens. W3schools claims that "The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement." - http://www.w3schools.com/php/php_includes.asp
but it doesn't seem to work like a copy as manualy copying gives other results (variable $rejon is accesible).
1) What exactly does require do and what are its limitations?
2) Most importantly - how do I retrieve that $rejon variable in two.php?
Works for me:
$ cat one.php
<?php
$rejon = 'this value came from POST';
require 'two.php';
$ cat two.php
<?php
echo $rejon . PHP_EOL;
$ php one.php
this value came from POST
The W3Schools description is, unsurprisingly, misleading. Nothing is copied. The contents of the file are read, evaluated, and inserted at the point of the require. With respect to variables, the PHP manual says this:
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. However, all functions and classes
defined in the included file have the global scope.
Which is why my example above works as it does.
To diagnose this issue, continue to simplify your code to reduce it to the simplest possible example. If you're trying to use $rejon in a function inside of two, then you need to make the variable global. Like:
global $rejon;
$rejon = $_POST['rejon'];
// now you have $GLOBALS['rejon'] everywhere
Side note, $_SESSION should not be necessary unless you're crossing a page refresh boundary.
You can do this by the following two ways
1.Using Session
You can store the data in the session and than you can use it in the another file two.php
one.php
<?php
session_start();
$rejon = $_POST['rejon'];
$_SESSION['rejon'] = $rejon;
?>
two.php
<?php
session_start();
echo $_SESSION['rejon'];
?>
2. Including that file
I have found that you are including the file two.php in your script. If you are including this file than you can directly use the variable $rejon
two.php
<?php
echo $rejon;
?>
You can use sessions http://php.net/manual/en/book.session.php or a constant http://php.net/manual/en/language.constants.php.
Utkarsh already provided some examples for sessions.
To define a constant you use the define() function.
define('CONSTANT_NAME', CONSTANT_VALUE);
As long as your constant is defined and included (if in another file) before you use it you can then call CONSTANT_NAME in your code to get the value.
In my php code there is a section which needs to be retrieved from another php file.
I tried accomplishing this by:
include "teams.php?id=".$matchid;
and in the teams.php
$matchid = $_GET['id'];
echo "MATCH ID IS ".$matchid;
The problem is when i open teams.php?id=".$matchid directly it displays the match id fine
however the include doesn't work - i checked the source code of the original page - no code is being inserted. Is there a way to do what i want? I need to get php code from another file whilst passing 2 variables onto that file
Problem
The problem is related to what $_GET really contains:
An associative array of variables passed to the current script via the URL parameters. (...)
And you do not pass $matchid to the script through URL... And you should not in this case.
Solution
But there is a way. PHP does not separate global variables among files, so variables available in one file are available also in the one included:
in file no. 1:
// Assume $matchid is defined
include "teams.php";
in file no. 2 (the one included):
// No need to redefine $matchid - it was defined in the first file
echo "MATCH ID IS ".$matchid;
Also make sure you add <?php at the beginning of the file (the closing tag is not required). Otherwise it will be treated as text and not executed.
The problem is that you aren't loading that page in the browser when you call the include function, so the variable you are appending is not being processed as a URL query param. You are really just taking everything inside teams.php and dumping it into the other file (the one including teams.php) at that position.
If you want to effectively pass something into teams.php then just declare a variable before the include.
Check out http://php.net/manual/en/function.include.php and all will become clear.
That's not how include's work. When you include a file, it's code is executed as if it was written in the same file it's being included in. So teams.php will have the variable $matchid when the including file has that variable, no need to pass it in. Also the way you called the include was incorrect. Doing what you did causes php to look for a file in the current directory called 'teams.php?id=0' (replace 0 with the $matchid value). This file does not exist, 'teams.php' exists, not the URI. It is possible to specify a url by prefixing it with 'http://' however the result would work with the code in teams.php as it would expect to be able to read the php source.
You can do like this include "include "teams.php?id={$matchid}"; and
$matchid = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING);
echo "MATCH ID IS {$matchid}";
If You will use this code, you will be safe from Injects too!
I hope you will apreciate this.
I am trying to do an include(dirname(FILE), '/../file.php?variable=VAR'), but it is unable to find the location when I use the variable.
The directory is located one above the current one where the file is. Is it possible to pass the variables through the include?
You can't, though you won't need this at all, because $_GET's scope is global [i.e. accessible from every script you run].
Just to be clear:
include($path) searches the filesystem for a resource, then processes it.
http://somesite.com/index.php?key=value is a URL, whose part after the ? sign is called query.
No.
By using include, you include the source code from the file as it is. I guess you want to define a function inside the included file and call it to get the result.
I am wondering if there is a way to pass a variable to a file you are including via include()?
I tried this but got an error:
include("header_alt.php?img=hey");
Is there a way to do that?
Thanks!
Just define your variable in the first file ; for instance, in temp.php :
<?php
$my_var = 10;
include 'temp-2.php';
die;
?>
And use it in the second file ; temp-2.php :
<?php
var_dump($my_var);
?>
And it should work : I'm getting this output, from temp-2.php :
int 10
The query-string syntax, using stuff like ?img=hey is used when you are requesting some data from a distant server (like when you are using your browser to surf on websites), not when including a file that is on the same server.
Smarty provides a really good mechanism for this sort of thing. Plus, using Smarty just makes for better php applications.
http://www.smarty.net/manual/en/language.function.include.php
Variables can be passed to included
templates as attributes. Any variables
explicitly passed to an included
template are only available within the
scope of the included file. Attribute
variables override current template
variables, in the case when they are
named the same.
All assigned variable values are
restored after the scope of the
included template is left. This means
you can use all variables from the
including template inside the included
template. But changes to variables
inside the included template are not
visible inside the including template
after the {include} statement.