Why does this work:
echo $session->name;
require_once('test.php');
//echos the name then loads the required page
But
var_dump($session->name);
in the code of test.php returns NULL.
I thought require_once pretty much plops all the code from the required page into the spot I told it to.
EDIT
$session instance is created before the require, outside of test.php. If I create a new instance of $session inside test.php it works. Glad it works but this still doesnt make sense to me, can anyone explain?
$session is not in the scope. include that script where you have initialized $session. or declare it as global in all scripts that will save the include just for $session. why not use $_SESSION though?
Dumb question: Have you already require_once'd test.php somewhere else in your script? If so, then it's possible that $session may not have been set when you included it the first time. Have you tried include('test.php') instead?
DEBUGGING EDIT:
You can validate the order things are being called in by trying the following:
In the caller.php (or whatever you call it) file:
echo "Debug 1";
echo $session->name;
require_once('test.php');
In test.php:
echo "Debug 2";
var_dump($session->name);
Which is printed first, Debug 1 or Debug 2?
Related
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.
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.
I'm looking for a way to access an array defined in an included PHP file, from outside this file. I've been Googling on that for a few hours but I didn't really find anything that answered my question.
I've tried using $GLOBAL['varname'] outside my script after using global $varname in the included file but it doesn't seem to work, got to say I'm a bit confused.
Is there any way I can do this in PHP?
Thanks a lot for the answer!
user $_SESSION variables. so you will be able to access your variables anywhere in your php application.. untill you unset it..
try this..
session_start();
$_SESSION['array'] = $array; //your array
now you can use this variable/array in any file of your project..
print_r($_SESSION['array']);
if you include a file in PHP you can access the variable the same way you would if it was in the same file..
File1 (foo.php):
<?php
$var = array('foo','bar');
File2:
<?php
require_once('foo.php');
print_r($var);
does this not work..?
I have a PHP script called customers.php that is passed a parameter via the URL, e.g.:
http://www.mysite,com/customers.php?employeeId=1
Inside my customers.php script, I pick up the parameter thus:
$employeeId = $_GET['employeeId'];
That works just fine. I also have an HTML file with a form that inputs the parameter, and runs another php script, viz:
<form method="post" action="listcustomers.php">
Employee ID: <input name="employeeId" type="text"><br>
<input type="submit" value="Show">
</form>
Then in my listcustomers.php script, I pick up the parameter so:
$employeeId = $_POST['employeeId'];
So far so good. But his is where I am stuck. I want to run my customers.php script, and pass it the parameter that I pave picked up in the form. I am sure this is really simple, but just cannot get it to work. I have tried:
include "customers.php?employeeId=$employeeId&password=password";
But that does not work. Nor does anything else that I have tried. Please help me.
You can't add a query string (Something like ?x=yyy&vv=www) onto an include like that. Fortunately your includes have access to all the variables before them, so if $_GET['employeeId'] is defined before you call:
include 'customers.php';
Then customers.php will also have access to $_GET['employeeId'];
PHP includes are really includes; they attach piece of code from that location to this location.
PaulPRO’s answer most likely tells what you want to achieve, but also other variables would be usable in the included file. So if you define $foo = "bar"; in index.php and include layout.php after that line, you could call this $foo variable in that layout.php file.
If you seriously want to pass an URL to the file, you can insert the URL into variable and in included file parse it with parse_url
EDIT: and yes, I do not suggest adding query params to actual include url as it starts to mess up with GET array and eventually you’ll just be confused what there should be and start smacking your head into wall.
Your include file will have access to the GET variables directly.
You can use $GLOBALS to solve this issue as well.
$tit = "Hello";
$GLOBALS["docTitle"] = $tit;
include ("my.php");
You can pass the value through Session
Like
<?php
$_SESSION['name']='peter';
$_SESSION['age']=28;
include('person_info.php');
?>
In person_info.php, start the session and put all session value in the variable and unset the session.
This is not so clean but this will work if you need to enter a static parameter:
if (true){
echo "<meta http-equiv='refresh' content='0;url=query_source.php?random=red%20bull' />";
}
else
{
echo "<meta http-equiv='refresh' content='0;url=query_source.php?random=blue%20bull' />";
}
Just put it within your source code for the page which calls the query_source.php.
Once again, it is NOT very clean...
Ok, maybe my brain is just shut off, but I can't get this to work.
Here's the complete code:
Page1.php:
<?php
$something = "hello";
include "Page2.php";
?>
Page2.php:
<?php
echo $something;
?>
Desired output (when navigating to Page1.php):
hello
The real output is blank. I have tried putting the global keyword everywhere, and nothing happens. Am I missing something?
I cannot replicate this error, just tried this on my localhost and copied and pasted your code from here. I suspect you have some sort of syntax error.
Turn on error reports and see if you get any errors.
I know this is a late answer, but I'm trying to do something similar. First of all, when you echo something you still have to put it in " ". Php will recognize it as a variable as long as you put the $.
Second, you're including page2.php in page1. Fantastic, but page2 does not recognize $something. Now, if you do it the other way, declare $something in page2, and then call it from page 1 after including it, it will run.
Modifying the variable would require something else...
I think the output is coming in page2.php . Am i right? this is because you are echoing a unset variable in page2.php you need to change the following data in order to make it work.
page1.php
<?php
include("page2.php");
echo $something;
?>
page2.php
<?php
$something="Hello";
?>
If you will use it and navigate the page 1.php then the output will be Hello
I had a similar problem running on local (Windows) where the values of an array did not follow past the include within the same process.
After switching the include path from http://localhost/www/example.php to C:/www/example.php, it works fine now.