Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save PHP variables to a text file

Tags:

file

php

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.

like image 352
Aadi Avatar asked Jun 08 '10 07:06

Aadi


People also ask

What is $$ variable in PHP?

Syntax: $variable = "value"; $$variable = "new_value"; $variable is the initial variable with the value. $$variable is used to hold another value.

How variables are stored in PHP?

A variable in PHP is a name of memory location that holds data. In PHP, a variable is declared using $ sign followed by variable name. The main way to store information in the middle of a PHP program is by using a variable.

What is $_ PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables.


2 Answers

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; 
like image 165
Sandeep Shetty Avatar answered Sep 19 '22 21:09

Sandeep Shetty


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)); 
like image 32
Christian Avatar answered Sep 16 '22 21:09

Christian