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

时间:2014-03-14 17:27:30

标签: php forms session text

这是一个冗长的问题,因为我完全迷失了!

概念:用户输入他们希望写入的文本文件,在提交时将其发送到用户可以创建形状并将其提交到文本文件的页面,然后使用该数据计算形状区域,选择的颜色等...

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

这就是我在主页上的内容:

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

3 个答案:

答案 0 :(得分:0)

将文件打开为&#34; r&#34;意思是只读你应该把它打开为写

fopen($txtFile, 'r+')

如果您希望在打开时截断文件,请将'r+'替换为'w+'

答案 1 :(得分:0)

关闭文件处理程序后,使用file_put_contents()函数更新文件。像这样:

fclose($file);
file_put_contents($txtfile, $_SESSION['serial']);

确保文件可写。

答案 2 :(得分:0)

试一试。

以下内容将写入取自TEST.txt会话变量的$write_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);