【问题标题】:PHP/Txt - How to save into session/load from sessionPHP/Txt - 如何保存到会话/从会话加载
【发布时间】:2014-03-14 17:27:30
【问题描述】:

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

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

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

这是我在主页上的内容:

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

【问题讨论】:

  • 你可以在一行中做到这一点$txtFile = $_POST['submittedTxtFile'] = $_SESSION['submittedTxtFile'];链接方法)然后只需使用你现在使用的$file = fopen($txtFile, "r")...你就可以摆脱$txtFile = $_POST['submittedTxtFile']; $_SESSION['submittedTxtFile']= $txtFile;
  • file_put_contents($txtfile, serialize($whatever))。这不是火箭科学……
  • @Fred-ii- 抱歉,您能否详细说明一下,因为我对此很陌生,所以不确定您希望我更改什么
  • 您的$file = fopen($txtFile, "r") 也存在错误,其中r 是只读的。您需要使用ww+,如下所述。另外,有问题的文件;这将取决于您要使用哪种格式。旁注:如果要添加到文件,需要使用aa+ 开关。
  • 但是我没有在那个页面上写任何东西,只是阅读使用 sn-ps 就像计算当前存在多少个形状......但是当我尝试添加一个新形状时,我得到这个文件不存在

标签: php forms session text


【解决方案1】:

以“r”打开文件意味着只读你应该以写打开它

fopen($txtFile, 'r+')

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

【讨论】:

    【解决方案2】:

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

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

    确保文件是可写的。

    【讨论】:

      【解决方案3】:

      试试这个。

      以下内容将写入一个名为 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);
      

      【讨论】:

        猜你喜欢
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-25
        • 2012-12-23
        相关资源
        最近更新 更多