首页 > 解决方案 > 如何使用按钮打开我在 php 中创建的最后一个文件

问题描述

我能够使用用户在表单中输入的数据创建一个文件。第一个输入字段接受用户输入的内容并将其作为文件的标题。内容或消息取自 textarea 标签并将其添加到此文件中,当我单击提交时,文件被创建。问题是我有另一个按钮,当我单击时应该能够显示我在上一步创建的文件的内容。我正在使用另一个提交按钮来尝试将文件的内容显示到网页上。

这是用于创建文件的代码。

if(isset($sub) && $fname && $txt){
    
    $myFile = fopen("$fname.txt", 'wb');
    fwrite($myFile, $txt);  
    fclose($myFile);

标签: phpfilesubmitfopen

解决方案


只需保存文件的路径,$_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"]);

推荐阅读