【问题标题】:How can i open the last file I created in php using a button如何使用按钮打开我在 php 中创建的最后一个文件
【发布时间】:2021-09-22 19:36:32
【问题描述】:
我能够使用用户在表单中输入的数据创建一个文件。第一个输入字段接受用户输入的内容并将其作为文件的标题。内容或消息取自 textarea 标签并将其添加到此文件中,当我单击提交时,文件被创建。问题是我有另一个按钮,当我单击时应该能够显示我在上一步创建的文件的内容。我正在使用另一个提交按钮来尝试将文件的内容显示到网页上。
这是用于创建文件的代码。
if(isset($sub) && $fname && $txt){
$myFile = fopen("$fname.txt", 'wb');
fwrite($myFile, $txt);
fclose($myFile);
【问题讨论】:
标签:
php
file
submit
fopen
【解决方案1】:
只需保存文件的路径,如果你想在整个会话中保存,可以使用$_SESSION。
session_start();
$path = "$fname.txt";
if(!$myFile = fopen($path, 'wb')) // Checks if the file can be opened
{
exit;
}
if (!fwrite($myFile, $txt)) // Checks if the write was successful
{
exit;
}
$_SESSION["recentFile"] = $path;
fclose($myFile);
现在您可以使用
访问最后一条路径
session_start();
echo file_get_contents($_SESSION["recentFile"]);