Viewed   87 times

I was wondering how to save PHP variables to a txt file and then retrieve them again.

Example:

There is an input box, after submitted the stuff that was written in the input box will be saved to a text file. Later on the results need to be brought back as a variable. So lets say the variable is $text I need that to be saved to a text file and be able to retrieve it back again.

 Answers

1

This should do what you want, but without more context I can't tell for sure.

Writing $text to a file:

$text = "Anything";
$var_str = var_export($text, true);
$var = "<?phpnn$text = $var_str;nn?>";
file_put_contents('filename.php', $var);

Retrieving it again:

include 'filename.php';
echo $text;
Sunday, December 18, 2022
2

Let's say you have two files a.php and b.php on same folder.

Code on the file b.php

<?php

echo "hi";

?>

and code on a.php

<?php
$data = file_get_contents('b.php');
echo $data;

You access a.php on browser.

What do you see? A blank page.

Please check the page source now. It is there.

But not showing in browser as <?php is not a valid html tag. So browser can not render it properly to show as output.

<?php
$data = htmlentities(file_get_contents('b.php'));
echo $data;

Now you can see the output in browser.

Sunday, September 11, 2022
 
4

Variables do propagate to the included files, so it must be, that the variable is NOT set when you call the include: try checking if so, then figure out why is the variable not set at that point.

For example, if you defined $logged inside the "if" block or inside a function, then it won't propagate outside of it: you must define it in the outermost scope (at the same level at which you call the include statement). And you must define it for the case that the user is not logged in, not only for the case when the user is logged in. If the variable is not initialized to false, the check if(!$logged) will issue warning. Say $logged = false; at the beginning of your work.

Friday, October 7, 2022
 
2

You probably want to try the PHP Tokenizer.

http://www.php.net/manual/en/ref.tokenizer.php

From an external script:

<?php

var_dump(token_get_all(file_get_contents('myscript.php')));

?>
Thursday, December 8, 2022
 
jimmont
 
27

Using the set at the command prompt will list all of your environment variables. So, you can just pipe the output of the set command to a file, like this:

set > "pathtofile.txt"
Sunday, October 23, 2022
 
vissi
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :