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.
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 = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);
Retrieving it again:
include 'filename.php';
echo $text;
Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).
Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.
$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));
(Sorry I can't comment just yet, otherwise I would)
To add to Christian's answer you might consider using json_encode and json_decode instead of serialize and unserialize to keep you safe. See a warning from the PHP man page:
Warning
Do not pass untrusted user input to unserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.
So your final solution might have the following:
$file = '/tmp/file';
$content = json_encode($my_variable);
file_put_contents($file, $content);
$content = json_decode(file_get_contents($file), TRUE);
for_example, you have anyFile.php, and there is written $any_variable='hi Frank';
to change that variable to hi Jack, use like the following code:
<?php
$content = file_get_contents('anyFile.php');
$new_content = preg_replace('/\$any_variable=\"(.*?)\";/', '$any_variable="hi Jack";', $content);
file_put_contents('anyFile.php', $new_content);
?>
Use a combination of of fopen, fwrite and fread. PHP.net has excellent documentation and examples of each of them.
http://us2.php.net/manual/en/function.fopen.php
http://us2.php.net/manual/en/function.fwrite.php
http://us2.php.net/manual/en/function.fread.php
Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)
Okay, so I needed a solution to this, and I borrowed heavily from the answers to this question and made a library: https://github.com/rahuldottech/varDx (Licensed under the MIT license).
It uses serialize() and unserialize() and writes data to a file. It can read and write multiple objects/variables/whatever to and from the same file.
Usage:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
See the github page for more information. It has functions to read, write, check, modify and delete data.
Related
I used this to write a array into a text file:
$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($newStrings, TRUE));
fclose($fp);
now i want to read it back in php just like i would read a normal array? how do i do it? I'm fairly new to this and im currently on a deadline to get something related tot this fixed, pls help.
var_export() would be valid PHP code that you could then include and work better than print_r(), but I recommend using JSON / json_encode(). serialize() would also work similar to JSON but isn't portable.
Write:
file_put_contents('file.txt', json_encode($newStrings));
Read:
$newStrings = json_decode(file_get_contents('file.txt'), true);
Use PHP serialize and unserialize to do this.
Writing to file:
$myArray = ['test','test2','test3'];
$fp = fopen('file.txt', 'w');
fwrite($fp, serialize($myArray));
fclose($fp);
Or slimmer:
file_put_contents('file.txt',serialize($myArray));
Reading it again:
$myArray = unserialize(file_get_contents('file.txt'));
Use json_encode() or serialize() on the data when you write it and then use json_decode() or unserialize() on the data when you have read it.
To see the differences check this question:
JSON vs. Serialized Array in database
There is a known way to include a file and capture its contents into a string while loading.
$string = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
https://www.php.net/manual/en/function.include.php
Is there a way to "include" contents loading them from a string instead of a file?
I mean something like this:
$string = file_get_contents("file.php");
include_from_string($string);
If you want the string to be parsed as PHP code, just like the contents of a file loaded with include(), then the function you need is eval().
Note that, unlike code loaded by include(), code executed by eval() automatically starts in PHP mode, so you don't need to (and shouldn't!) prefix it with <?php. If you want to emulate the behavior of include() exactly, you can prefix the string to be eval()ed with ?> to leave PHP mode:
$string = file_get_contents( 'somefile.php' );
eval( '?>' . $string );
Also note that eval() is a very dangerous function to play with! While in this specific case it shouldn't be any more risky than include() itself is, using eval() on any string that might even possibly contain unsanitized (or insufficiently sanitized) user input is extremely dangerous, and may be exploited by attackers to execute malicious code on your system and thereby gain control of it.
This might not be what you are looking for but I got "work around" for it.
Just create temporary file with tempnam() which you will include and then unlink().
$path = "somefile.php";
$stringFile = file_get_contents($path);
$pathTmp = tempnam("tmp/", ""); // you pass directory in which you will store tmp files for me it's "tmp/"
$file = fopen($pathTmp, "w+");
fwrite($file,$widget);
fclose($file);
include $pathTmp; // include the file, and PHP will be automatically parsed
unlink($pathTmp); // delete file
THIS IS WRONG:
I'm not sure if it's good practice (but hack damn, it's simple) because no one suggested it but it's better then eval() which is basically "code hazard".
THIS IS RIGHT:
As #Chris Harrison commented this is security risk and it's equal to eval(). So you could basically do this:
eval($string);
This is a simple example for you, if you pass inside the eval() this will execute the code in the string variable.
<?php
//here your PHP Code goes
$string = get_include_contents('somefile.php');
//evaluating the string this will work
eval($string); //output
This is not equivalent to using include. Here's the problem: eval() takes the provided PHP, and executes it in the current environment. Thus, any globals, functions, classes, what-not, you have defined prior to the eval() are available for the processor. This is all good, and, upon return, the only thing left of the original (evel'd) string are the results of any echo (or equivalent) statements.
This is NOT the same as an include. There the file contents are merged with your source code and that is passed to eval(). Very, very different. The easiest way to see this is to define your string as 'class fu { static function bar() { echo "wow"; } ]' Put this in a file and call fu::bar() and you'll get 'wow' displayed. At the same point in your code, if you do an eval('class fu ...') and call fu::bar() from your code you'll get "Fatal error: Call to private method fu::bar() from context ..."
But, as long as you don't need to interact with the 'include' the results will appear the same.
Just echo whatever you want instead of include inside your function!
UPDATE
Your function should look like this:
$string = "Whatever";
$str = get_var($string);
function get_var($str) {
ob_start();
echo $str;
return ob_get_clean();
}
Good morning all, i have a new question:
I'm trying to save into mysql a set of data coming from a SIMBAD database query (it's a stellar objects dataabse).
If you enter this url into the browser: http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=hd%201&OutputMode=VOTable
you get a result formated with separate lines, but if you use
<?php
$cadaart = 'http://simbad.u-strasbg.fr/simbad/sim-id?output.format=ASCII&Ident=hd%201';
$handler = curl_init($cadaart);
$response = curl_exec ($handler);
curl_close($handler);
echo $response;
?>
or a simple file_get_content and echo the response you get a single line with all information, which makes me impossible to parse... Any idea on how to solve this?
Thanks.
The string is already with line-break,
you can use file to convert contents from that URL into an array (each line is an array element)
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
It's probably just the difference between an LF and a CRLF. The output from your URL is LF, which, in where you're viewing it (browser?), is probably not parsed as a new line.
Try $response = str_replace("\n", "\r\n", $response); and see if this makes any difference
I'm trying to figure out how to stored php values in a string/file.
I have a text file with "var1=foo&var2=foo2" etc in it, is there a way to read the values?
You could use file_get_contents() to open the file and parse_url() to parse the contents into an associative array.
$file = file_get_contents('file.txt');
parse_str($file, $params);
CodePad.
Or if you can change it, theres always serialize() and unserialize()
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.
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 = "<?php\n\n\$text = $var_str;\n\n?>";
file_put_contents('filename.php', $var);
Retrieving it again:
include 'filename.php';
echo $text;
Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).
Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.
$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));
(Sorry I can't comment just yet, otherwise I would)
To add to Christian's answer you might consider using json_encode and json_decode instead of serialize and unserialize to keep you safe. See a warning from the PHP man page:
Warning
Do not pass untrusted user input to unserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.
So your final solution might have the following:
$file = '/tmp/file';
$content = json_encode($my_variable);
file_put_contents($file, $content);
$content = json_decode(file_get_contents($file), TRUE);
for_example, you have anyFile.php, and there is written $any_variable='hi Frank';
to change that variable to hi Jack, use like the following code:
<?php
$content = file_get_contents('anyFile.php');
$new_content = preg_replace('/\$any_variable=\"(.*?)\";/', '$any_variable="hi Jack";', $content);
file_put_contents('anyFile.php', $new_content);
?>
Use a combination of of fopen, fwrite and fread. PHP.net has excellent documentation and examples of each of them.
http://us2.php.net/manual/en/function.fopen.php
http://us2.php.net/manual/en/function.fwrite.php
http://us2.php.net/manual/en/function.fread.php
Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)
Okay, so I needed a solution to this, and I borrowed heavily from the answers to this question and made a library: https://github.com/rahuldottech/varDx (Licensed under the MIT license).
It uses serialize() and unserialize() and writes data to a file. It can read and write multiple objects/variables/whatever to and from the same file.
Usage:
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
See the github page for more information. It has functions to read, write, check, modify and delete data.