I want to be able to send a few variables to a file through file_get_contents()
.
This is firstfile.php:
<?php
$myvar = 'This is a variable';
// need to send $myvar into secondfile.php
$mystr = file_get_contents('secondfile.php');
?>
This is secondfile.php:
The value of myvar is: <?php echo $myvar; ?>
I want the variable $mystr
to equal 'The value of myvar is: This is a variable'
Is there any other function that will let you do this in PHP?
There is a big difference between getting the contents of a file and running a script:
include
— this PHP directive runs the specified file as a script, and the scope is the same as the scope where the include
call is made. Therefore, to "pass" variables to it, you simply need to define them before calling include
. include
can only be used locally (can only include files on the same file system as the PHP server).
file_get_contents
— When getting a file locally, this simply retrieves the text that is contained in the file. No PHP processing is done, so there is no way to "pass" variables. If you inspect $myvar
in your example above, you will see that it contains the exact string "<?php echo $myvar; ?>
" — it has not been executed.
However, PHP has confused some things a little by allowing file_get_contents
to pull in the contents of a "remote" file — an internet address. In this case, the concept is the same — PHP just pulls in the raw result of whatever is contained at that address — but PHP, Java, Ruby, or whatever else is running on that remote server may have executed something to produce that result.
In that case, you can "pass" variables in the URL (referred to as GET
request parameters) according to the specifications of the URL (if it is an API, or something similar). There is no way to pass variables of your choosing that have not been specified to be handled in the script that will be processed by that remote server.
Note: The "remote server" referred to MAY be your own server, though be careful, because that can confuse things even more if you don't really know how it all works (it becomes a second, fully separate request). There is usually not a good reason to do this instead of using include
, even though they can accomplish similar results.