PHP使用表单输入写入文件 点击提交按钮提前关闭文件问题求助
问题根源
你的逻辑嵌套顺序存在错误:fileInsert的触发判断完全嵌套在fileOpen的判断分支内。当你点击写入提交按钮时,新的POST请求仅携带fileInsert和输入的内容参数,没有fileOpen参数,所以整个打开文件的分支都不会执行,写入逻辑和成功提示自然不会触发,页面就会回到初始无文件打开的状态。
另外你当前的写入表单没有携带已打开的文件名参数,提交写入请求时也丢失了要操作的文件名称信息。
修复步骤
- 调整逻辑判断顺序,优先处理写入请求
- 在打开文件后渲染的写入表单中添加隐藏字段,存储当前打开的文件名,确保提交写入时能拿到要操作的文件
- 将写入逻辑从打开文件的判断分支中独立出来,避免参数缺失导致逻辑不执行
修正后代码
<!DOCTYPE html> <html> <head> <title>File Creator</title> </head> <body> <h1>File Creator</h1> <form action="" method="post"> <label for="fileName">Enter the name of the file you would like to open including the extension:</label><br /> <input type="text" name="fileName"><br /> <input type="submit" value="Open File" name="fileOpen"> </form> <?php // 优先处理写入请求 $writeMsg = ''; if(isset($_POST['fileInsert'])) { $fileName = $_POST['fileName']; $fileInput = $_POST['fileInput']; if (is_file($fileName)) { $myfile = fopen($fileName, "w"); fwrite($myfile, $fileInput); fclose($myfile); $writeMsg = "Done! <br />"; } } // 处理打开文件请求 $currentOpen = 'None'; $insertForm = ''; $errorMsg = ''; if(isset($_POST['fileOpen'])) { $fileName = $_POST['fileName']; $currentOpen = $fileName; if (is_file($fileName)) { // 写入表单添加隐藏字段存文件名 $insertForm = "<form action='' method='post'> <input type='hidden' name='fileName' value='{$fileName}'> <label for='fileInput'>File is open!<br />Insert up to 40 characters:</label><br /> <input type='text' name='fileInput' maxlength='40'><br /> <input type='submit' value='Submit' name='fileInsert'><br /><br /> </form>"; } else { $errorMsg = "File does not exist. <br /><br /> <a href='start.php'><button>Return to Homepage</button></a>"; } } // 统一渲染状态 echo "<h3>Currently open: {$currentOpen}</h3><br />"; echo $writeMsg; echo $insertForm; echo $errorMsg; ?> </body> </html>
额外优化建议
- 可以添加文件权限校验,避免无权限写入时报错
- 对输入的文件名做路径限制,防止越权操作敏感文件
- 写入完成后可以保留当前文件打开的状态,不需要用户重复输入文件名打开
内容的提问来源于stack exchange,提问作者RiZzOu
相关产品推荐
相关产品推荐

