Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

file get contents - PHP sending variables to file_get_contents()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...