php将变量输出到txt中,javascript – 通过.php将变量值发送到.txt文件

“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.”

好的,我很清楚你想在这里做什么.

重要的旁注:请仔细和完整地回答我的回答;我可能没有完全掌握你想要达到的目标,所以我的答案有两种选择.

这是你需要做的:

首先使用is_numeric()检查输入是否为数字.

然后分配变量并使用$_POST [‘variableToPass’]数组添加POST量.

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表单

var variableToPass= 1;

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

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

但是,使用此方法将继续添加/附加到文件.如果这不是所需的结果,则需要删除以下点:

$content .= $variableToPass. PHP_EOL;

^

读作:

$content = $variableToPass. PHP_EOL;

另外,如前所述;这一行:

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

应该读作:

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

> getElementById区分大小写.

选项2使用“amount”输入中的数字写入文件.

这将从输入中写入任何数字并将其写入文件,而不是附加到文件.

如果未插入数字且仅通过单击提交按钮,将写入您在var variableToPass = 1中定义的数字;

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);

脚注:

>如果您对此有任何疑问,或者我可能没有完全理解;让我知道.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值