Save PHP Variables to a Text File

Save PHP variables to a text file

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;

How to write a variable value in a text file with php

Brief Explanation:

You are trying to combine two separate languages as if both were client-side "as needed" scripting languages.

Javascript is client-side, and as such, will run based on event listeners or any other defined parameters. PHP is server-side, and as such, will run when the file is parsed. This means that your PHP is already processed and out of the picture by the time the Javascript even comes into the picture.

What is happening in your script presently:

The file is parsed, PHP is identified, and runs first. Immediately upon running, the file gets written to. PHP defaults to the text-value of "textBox.value" as it is not an actual variable (which would be preceded with $ if it were). In all honesty, it should be returning an error that "textBox.value" means nothing, essentially (PHP is not strict, so it makes a lot of assumptions). It's not, however, because it's assuming you are referencing a Constant. After the PHP is processed, the DOM is processed and sent to the browser. The PHP does not even exist at this point and has been stripped away from the DOM (rightfully so - you'd NEVER want PHP to be visible to a client).

What to do:

You cannot run this PHP snippet every time you want to increment/decrement the value with the PHP being inside of the same file (at least not without a form submit, or something to "catch" the request -- my response will be based on the fact that you simply want it to write when clicking, instead of submitting a form every time). You must change your code. One thing I'd suggest is placing the PHP inside of its own file. Then, upon incrementing/decrementing the value, you use AJAX to actually hit that file (thus triggering a file write).

Example:

index.html:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>

<script>

$("#decreaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) -1);
writeToFile($("#textBox").val());
})
$("#increaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) +1);
writeToFile($("#textBox").val());
})

function writeToFile(value){

$.ajax({
url: 'write.php?v=' + value,
type: 'GET',
dataType: 'json',
success: function(ret){
alert('Success!');
},
error: function(ret){
alert('Error!');
}
});

}

</script>

</body>
</html>

write.php:

<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");

$txt = "value = " . $_GET['v'];
fwrite($myfile, $txt);
fclose($myfile);
?>

Note the Changes:

I am using JQuery in my example. I apologize if you wanted strictly native Javascript.

Also please note, I changed the PHP. You had two writes, which was unnecessary and would take more time. File Input/Output is costly, and should be used minimally. In fact, in this example, I'd personally have just written to a database. However, you did not ask for a separate solution, so I simply provided an example similar to what you had written.

Random Thoughts

You can use decrement/increment instead of what you're doing as well. Like so:

<script>

decreaseNumber.onclick = function() {
textBox.value--;
alert(textBox.value);
}
increaseNumber.onclick = function() {
textBox.value++;
alert(textBox.value);
}

</script>

Save a with variable in a text file php

I want to save "$my variable" in the file

If I understand you correctly, you want the resulting output to include quotes? You'd need to include the quotes in the value being saved. Perhaps something like this:

file_put_contents("mytext.txt","\"$variable\"");

or:

file_put_contents("mytext.txt",'"' . $variable . '"');

The difference is mostly a matter of personal coding style preference. Qouble-quoted strings expand variables, but your double-quotes would need to be escaped. Single-quoted strings wouldn't need to escape the double-quotes, but don't expand variables.

A string value doesn't include quotes, it's denoted to the compiler/interpreter/etc. by quotes. For the value itself to output quotes they need to be added to the value.

Send variable value to .txt file through .php

"It is because I want to save the variable to be able to show it to all users on the website, so to do this I have the default value which is 1 and then I have a text input, which only allows numbers which are the variable+1 so lets say the default is 1, then I will put 2 into the input and then the .php file will get this input of 2 and save it into the .txt file, where after that the variable in the javascript will get this variable in the .txt file, and turn the new value into the variable. A bit complicated but basically it is just to save the variable for all users and not locally."

Ok, I have pretty good idea as to what you want to do here.

Important sidenote: Please go over my answer very carefully and in its entirety; I may not have fully grasped what you want to achieve here, so there are two options in my answer.

Here's what you need to do:

First check to see if the input is numeric by using is_numeric().

Then assign variables and add the POST amount with the $_POST['variableToPass'] array.

PHP

<?php 

if(isset($_POST['amount']) && is_numeric($_POST['amount']) ){

$amount = $_POST['amount'];

}

else{
echo "It is not numeric. Please click back and enter an integer.";
exit;
}

$variableToPass1 = $_POST['variableToPass'];

$variableToPass = $variableToPass1 + $amount;

$filename = "textFilePass.txt"; // make sure this file exists before executing
$content = file_get_contents($filename);
$content .= $variableToPass. PHP_EOL;
file_put_contents($filename, $content);

HTML form

<form id="payment-form" action="chargeCard.php" method="POST" name="payment-form">
<input type="text" name="amount" id="amount" />
<input type="hidden" id="variableToPass" name="variableToPass" value="variableToPass"/>
<input type="submit" name="submit" value="Submit"/>
</form>

<script type="text/javascript">

var variableToPass= 1;

document.getElementById("variableToPass").innerHTML = variableToPass;
document.getElementById("variableToPass").value = variableToPass;

</script>

However, using this method will keep adding/appending to the file. If this isn't the desired result, you will need to remove the dot in:

$content .= $variableToPass. PHP_EOL;
^

to read as:

$content = $variableToPass. PHP_EOL;

Plus, as already stated; this line:

document.getElementByID("variableToPass").value = variableToPass;

should read as:

document.getElementById("variableToPass").value = variableToPass;
  • getElementById is case-sensitive.

Option 2 Using the number from the "amount" input to write to file.

This will write whatever number from the input and write it to file, and not appending to it.

If a number is not inserted and by clicking the submit button only, will write the number you've defined in var variableToPass= 1;

<?php 

if(isset($_POST['amount']) && is_numeric($_POST['amount']) ){

$variableToPass = $_POST['amount'];

}

else{

$variableToPass = $_POST['variableToPass'];

}

$filename = "textFilePass.txt";
$content = file_get_contents($filename);

$content = $variableToPass. PHP_EOL;

file_put_contents($filename, $content);

Footnotes:

  • If you have any questions about this, or that I may not have fully understood; let me know.

Saving variable value in a text file using PHP

The first issue is that in your JQuery you actually assigning the var1 variable to 'Info'
so the $_POST array will contain this rather than var1.

You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.

<?php   
$var1 = "";
$filename = "js/test.txt";

// Get the correct $_POST object
if (isset($_POST['Info']) {
$var1 = $_POST['Info'];
}

// If the variable is not empty try to write your file
if (!empty($var1)) {
if(!$file = fopen($filename,"w")) {
$msg = "Cannot open file");
} else if (fwrite($file,$var1) === false) {
$msg = "Cannot write to file");
} else {
$msg => 'all was good'
}

fclose($file);

$result = array(
'error' => 'false',
'msg' => $msg
);
} else {
$result = array(
'error' => 'true',
'msg' => 'Info was empty'
);
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";

PS: Not tested this so fingers crossed there are no typos.

read text from file via .php and store parts in variable

Your code would look like something like this:

<?php

$handle = fopen("inputfile.txt", "r");
$lineVariables = [];
if ($handle) {
while (($line = fgets($handle)) !== false) {
$tmp = explode('=', $line);
$lineVariables[trim($tmp[0])][] = trim($tmp[1]);
}
fclose($handle);

$result = [];
foreach ($lineVariables as $key => $variable) {
$result[$key] = implode(', ', $variable);
}

echo '<pre>' . print_r($result, true) . '</pre>';
} else {
// error opening the file.
}

Output:

Array
(
[1] => 19-10-18 10:02:06, 19-10-18 10:03:06, 19-10-18 10:04:06
[2] => +1.313026E+00 l/s, +1.266786E+00 l/s, +1.597391E+00 l/s
[3] => +1.671796E-01m/s, +1.612923E-01m/s, +2.033861E-01m/s
[4] => +1.500691E+02m3, +1.501403E+02m3, +1.502291E+02m3
[5] => +1.501138E+02m3, +1.501850E+02m3, +1.502738E+02m3
[6] => +0.000000E+00m3, +0.000000E+00m3, +0.000000E+00m3
)

Explanation

In the while cycle you read the lines with this:

$line = fgets($handle)

Then you need to process these lines. Since the index of the variables is the first character separated from the line variables you would like to add to the lines, you can use explode function using the '=' character as a delimiter.

Then in the $tmp array you will have 2 elements:
$tmp[0] will contain the indexes of the result. And $tmp[1] will contain the rest of the line.

For example the first line:

$tmp[0] // contains 1
$tmp[1] // contains 19-10-18 10:02:06

After the while cycle, our $lineVariables will look like this:

Array
(
[1] => Array
(
[0] => 19-10-18 10:02:06
[1] => 19-10-18 10:03:06
[2] => 19-10-18 10:04:06
)

[2] => Array
(
[0] => +1.313026E+00 l/s
[1] => +1.266786E+00 l/s
[2] => +1.597391E+00 l/s
)

[3] => Array
(
[0] => +1.671796E-01m/s
[1] => +1.612923E-01m/s
[2] => +2.033861E-01m/s
)

[4] => Array
(
[0] => +1.500691E+02m3
[1] => +1.501403E+02m3
[2] => +1.502291E+02m3
)

[5] => Array
(
[0] => +1.501138E+02m3
[1] => +1.501850E+02m3
[2] => +1.502738E+02m3
)

[6] => Array
(
[0] => +0.000000E+00m3
[1] => +0.000000E+00m3
[2] => +0.000000E+00m3
)

)

Now you can close the file and focus on formating the result to the desired look. We are going to store the result in the $result variable, which is an array, and one element of the array will represent one desired result, and the indexes on the array will be the reference to the first number character of the lines.

To append the elements of the $lineVariable for each line, we can use the implode function, which is kind of the opposite of the explode function. For one single this will convert this:

Array
(
[0] => 19-10-18 10:02:06
[1] => 19-10-18 10:03:06
[2] => 19-10-18 10:04:06
)

Into this one single line of string:

19-10-18 10:02:06, 19-10-18 10:03:06, 19-10-18 10:04:06

So we just go through on our prepared $lineVariables and process the elements to the desired format.

That's it.

PHP - write variable output to file

You only write out one line to the file. You probably want something like this:

$myFile = "/var/www/test/out.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
if ($fh) {
while ($row = getrow()) {
$content = $rows['text'];
fwrite($fh, $content); // perhaps add a newline?
}
fclose($fh);
}

So, open the file, write all your stuff in it, then close it.

Using PHP to write query string values to a .txt file and save

As simple as:

$url_value = "This is some value\n";
file_put_contents("/your/filename/here.txt", $url_value, FILE_APPEND );

See file_put_contents() for more information.

save content of a textarea to .txt file using PHP

You are not actually submitting the form, you are only passing the SubmitFile parameter as a GET parameter when you click the link. The easiest thing to do is replace the link with a submit button, and change your PHP to look for that parameter in the POST.

If you really need to use a link to submit the form, you will need to employ some javascript to cancel the default event on the link and submit the form. In that case, you will need to add the SubmitFile parameter as a hidden field.

<form method="POST" action="">
<div data-label="Index.php" class="demo-code-preview" contentEditable="true">
<pre><code class="language-html">
<textarea name="content">
<?php
$file = "index.php";
echo(htmlspecialchars(file_get_contents($file)));
?>
</textarea>
</code></pre>
</div>
<!--
This does not submit the form, it only makes a get request with the SubmitFile parameter.
You need ot submit the form and send the SubmitFile in the post, or add the SubmitFile
parameter to the form action if you really want to see it in the GET params.

<a href="?SubmitFile=true" class="bar-anchor" name="SaveFile"><span>Save</span></a>
-->
<button type="submit" name="SubmitFile">Save</button>
</form>

<?php
/*
* This will be true if the parameter is in the GET, but does not guarantee that
* the form was posted, so you cannot rely on this as a GET parameter.
* Change it to POST in the markup and here.
*
* if (isset($_GET['SubmitFile']))
*/
if (isset($_POST['SubmitFile']))
{
$content = $_POST['content'];
echo "<script>console.log('" . $content . "' );</script>";
$file = "myfile.txt"; // cannot be an online resource
$Saved_File = fopen($file, 'a+');
fwrite($Saved_File, $content);
fclose($Saved_File);
}
?>



Related Topics



Leave a reply



Submit