answersLogoWhite

0


Best Answer

Saving and retrieving PHP variables to and from a text file is bad programming practice in most cases, and can have repercussions (for example, the possibility of a variable changing between any two times running a script, and the script not being prepared for the new value).

There are better alternatives available, such as using a database system like MySQL, or a more standardized "text file" system using INI files. See the related links for information on MySQL and INI files. With that in mind:

There are many routes to making a script that retrieves and saves PHP variables in a text file, but a simple and common one may use the functions file_get_contents and file_put_contents, along with others like preg_match.

file_get_contents($filename) can be used to get the variables (and any other content) in our text file.

file_put_contents($filename) can be used to save variables to our text file.

preg_match($pattern, $string) can be used to validate a string and see if it matches the specified pattern.

See the related links for more information on these variables.

Before actually writing the script, a format of writing our variables (and their values) should be planned out. Simply put, what should your text file look like? For this example, we'll assume a style like this:

var1 = "something"

var2 = TRUE

var3 = 59

The style rule we're going to use here is the name of a variable, followed by a space, an equal sign, and another space, then the PHP syntax of a variable value (var1 will be a string, var2 will be a boolean, var3 will be an integer, and such). A new line specifies a new variable declaration.

Now lets go ahead and write our script. The one in this example will be called "index.php", but any name will do.

index.php

// First, lay out where our text file is for future use

$path = 'vars.txt';

// Create a function that will take the contents of our text file and transform it into PHP variables

function get_vars() {// This allows us to access the path variable in this custom functionglobal $path;// Get the actual contents of the text file and put it in a variable$contents = file_get_contents($path);// Seperate the content line-by-line$contents = explode("\n", $contents);// Take each line and evaluate itforeach ($contents as $key=>$line) { // Check if the syntax of the line is correct with a regular expressionif (!preg_match('/^[^0-9][A-Za-z0-9_]* = (TRUE|FALSE|NULL|[0-9]*|".*")$/', $line) { // Stop the function so we don't parse any bad syntaxreturn FALSE;

}

// Divide the line by spaces; there should be three divisions

$divisions = explode(' ', $line);

// Now lets give the divisions their rightful names

$varname = $divisions[0];

$value = $divisions[2];

// Lets assign the variable in PHP depending on its value type

if ($value NULL) {$value = 'NULL';

}

elseif (is_int($value)) {$value = $value;

}

elseif (is_str($value)) {$value = '"' . $value . '"';

}

// If the value isn't formatted yet, the value cant be contained by our format

else {return FALSE;

}

// Add the formatted value to the line

$line .= $value;

// Add the line to the file's new content and then a new line

$content .= $line . "\n";

// Repeat this loop if there are more variables to add

}

// Now put the variables in the text file

if (!file_put_contents($path, $content)) {// Something went wrong with putting the content inreturn FALSE;

}

}

// Now play with the functions!

get_vars();

echo $var1; // echos "something" if using example text file from earlier

$var2 = FALSE;

$var3 = 60;

if (!save_vars('$var2,$var3')) {exit('Variables were not saved!');

}

exit('Variables were saved!');

?>

This is a very simple way of going about retrieving and saving PHP variables in text files; its not perfect.

If you're more experienced, toy around with the code and make it more advanced!

User Avatar

Wiki User

12y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How do you retrieve and save PHP variables using text files?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Basic Math

What is the purpose of a JRE download?

The purpose of a JRE download is to save a particular file in a computer or hard drive. Files can include, but are not limited to , music, pictures, and videos.


How do you keep the value of a variable between different executions of the same PHP file?

If you want to save a variable to be used in the same script at different executions by the same user, you should try using sessions. Start a session (session_start()) and retrieve the variable in question (for example, $_SESSION['var']). Throughout the script, edit the variable ($_SESSION['var']) and it will automatically be saved for the next execution by the same user.Alternatively, if you want the value of the variable to be accessed by all users (and allow all users to edit the variable), do as stated above, but before starting the session, define a session name with the session_name() function. All users will refer to the session defined in the session name, thus using the same variable despite the user.See the related links for further help using sessions.


What is the difference between the save option and the save as option in MSWord?

When you do a save, the changes are applied to the document you originally opened. When you do a 'save as', you have to choose a name and a location where a copy of the document will be saved; this copy will have changes you are currently making to the document. You can then exit the document without saving, and your original document is unchanged. The copy that you 'save as' is still intact, with changes. You can also do a 'save as' without making any changes, just to have another copy of the document existing with a new name and/or location.


How much do you have to save each month to have 25000?

The answer depends on how long you save for, and since you have not bothered to share that crucial bit of information, I cannot provide a more useful answer.


If Olivia's take-home pay is 2460 per month what is the minimum amount per year that she should save?

The minimum she could save would be zero, if she spent all her money.

Related questions

How do SANs save and retrieve files faster than NAS devices?

imposible


Why do SANs save and retrieve files fastewr than NAS devices?

D


Where do the files do when you put them on your lg ks360 using your laptop?

well you pick the files you want to save it in then you got to where your save it on the lg and it will be there


If your computer goes down can you save your iTunes on a new computer?

Yes, you can retrieve your files. But it also depends on the problem of your computer why it crashes. In these matter please refer to a Technical Personnel near you. Because they have a knowledge on how to retrieve it.


How can you download and save vid files using their URL?

With http://www.keepvid.com you cand save vid from anywhere


Can you load different save files in minecraft beta?

Yes. The files save locally, and you can have multiple save files in one computer.


How do you print an assembly from solidworks on the uPrint 3D printer?

Am not sure if the uPrint 3d printer has an option of importing solidworks files, but it will definitely import .stl files. you can save your assembly as .stl by using the save as option and choose .stl in "save as type". Hope this helps.


Do smart TVs save files streamed to them?

No, Smart TVs do not save files that are streamed to them.


How do you create a game save for Game Boy Advance using an Action Replay?

You aren't able to save game files to a action replay, gameshark,etc.


How do you save your files in the Photoshop?

Go - File - Save or SAVE AS


Does Super Mario RPG for SNES have multiple save files If so how many?

Yes, it does have save files. You get 4 spaces to save.


Will you lose your files if you reinstall iTunes?

yes. it will save your files.