PHP/Txt-如何保存到会话/从会话加载

PHP/Txt-如何保存到会话/从会话加载,php,forms,session,text,Php,Forms,Session,Text,这是一个相当冗长的问题,因为我完全迷路了 概念:用户输入一个他们想要写入的文本文件,一旦提交,他们将被发送到一个页面,用户可以在该页面上创建形状并将其提交到文本文件,然后使用这些数据计算形状区域、选定的颜色等 问题是如何写入会话中的文本文件 这是我在主页上看到的内容: <?php // This line starts the session session_start(); //The below calls the file $txtFile = $_POST['submitt

这是一个相当冗长的问题,因为我完全迷路了

概念:用户输入一个他们想要写入的文本文件,一旦提交,他们将被发送到一个页面,用户可以在该页面上创建形状并将其提交到文本文件,然后使用这些数据计算形状区域、选定的颜色等

问题是如何写入会话中的文本文件

这是我在主页上看到的内容:

<?php

// This line starts the session

session_start();

//The below calls the file

$txtFile = $_POST['submittedTxtFile']; 
$_SESSION['submittedTxtFile']= $txtFile;
$file = fopen($txtFile, "r") or exit("That file does not exist");

include_once 'classShapeCollection.php';

//Creates the shapecollection
$shapes = new ShapeCollection();

//These lines get the called file, unserialize the $shapes and serialize them again before entering them into the session.

$buffer = fgets($file);

//Checking if there are any contents in the file

if($buffer)

    {
    $shapes = unserialize($buffer); //unserialize takes Text and turns it into an object
    $_SESSION['serial']= serialize($shapes); //Serialize takes the objects and converts them into Text
    }
    else //if there is nothing in the file, the session serialises the new ShapeCollection
    {
    $_SESSION['serial']= serialize($shapes);
    }

// Closes the called file
fclose($file);
?>

以“r”形式打开文件意味着只读,您应该以“写”方式打开文件

fopen($txtFile, 'r+')

或者将
'r+'
替换为
'w+'
如果要在打开文件时截断文件

关闭文件处理程序后,请使用file\u put\u contents()函数更新文件。像这样:

fclose($file);
file_put_contents($txtfile, $_SESSION['serial']);
确保文件可写。

试试看

以下内容将写入名为
TEST.txt的文件,该文件取自
$write\u session=“TEST”会话变量

以你自己为基础,我相信你会让它按照你想要的方式工作,但这基本上就是它工作的方式

<?php
session_start();

$_POST['submittedTxtFile'] = "file.txt"; // generic filename
$txtFile = $_POST['submittedTxtFile'];
$_SESSION['submittedTxtFile']= $txtFile;
$write_session = "TEST";

$_SESSION['write_session_write'] = $write_session;

$file = fopen($txtFile, "r") or exit("That file does not exist");

echo $_SESSION['submittedTxtFile'];

$file2 = $_SESSION['write_session_write'] . ".txt";
file_put_contents($file2, $write_session);

您可以在一行中完成此操作
$txtFile=$\u POST['submittedTxtFile']=$\u会话['submittedTxtFile']
(链接方法)然后只使用您现在使用的
$file=fopen($txtFile,“r”)…
然后您就可以摆脱
$txtFile=$\u POST['submittedTxtFile']$_会话['submittedTxtFile']=$txtFile
文件\u放入内容($txtfile,serialize($whatever))
。这不是rocketscience…@Fred ii-对不起,你能详细说明一下答案吗?因为我对这个问题很陌生,所以不确定你想让我改变什么。你的
$file=fopen($txtFile,“r”)
也有一个错误,其中
r
是只读的。您需要使用
w
w+
,如下所述。另外,有问题的文件;这将取决于您要使用的格式。旁注:如果你想添加到一个文件中,你需要使用
a
a+
开关。但是我没有在那页上写任何东西,只是在阅读中使用一些片段,比如计算当前存在的形状数。。。但是,当我尝试添加一个新形状时,我得到一个文件不存在的结果