PHP/Txt - How to save into session/load from session - php

This is quite a long-winded question as im completely lost!
The concept: User inputs a text file they wish to write to, upon submitting they are sent to a page where users can create shapes and submit them to the text file, this data is then used to work out the shapes area, colour that was selected etc...
Issue is how do i write to a text file that is in the session?
This is what i have on the home page:
<?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);
?>

Opening the file as "r" means read only you should open it as write
fopen($txtFile, 'r+')
Or replace 'r+' with 'w+' if you want file to be truncated when opened

After closing the file handler, use file_put_contents() function to update the file. Like this:
fclose($file);
file_put_contents($txtfile, $_SESSION['serial']);
Make sure the file is writable.

Give this a try.
The following will write to a file called TEST.txt taken from the $write_session = "TEST"; session variable.
Base yourself on it, am sure you will get it to work the way you want it to, but that's basically how it will work.
<?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);

Related

My fopen function works, but the fwrite function doesn't

So I'm trying to create a file and write code into that file whenever a user submits a register and successfully moves on to the activation stage. I'm doing this so that I can store all of the variables and information in my registration php file into the file I create. This is relevant code of the signup form:
#$file is set in removed code
$filename = '../' . $file;
fopen($filename, "w") or die("<h1 style='text-align: center; color: red;'>There has been an error creating your user files. Try again later.</h1>");
$content = "
<?php
potato
?>
";
fwrite($filename, $content);
Everything works, except for the fwrite() function. I looked at the file I created, and nothing appears in it. What's going on?
fopen() returns a stream resource bound to $filename. When you call fwrite(), the first parameter it takes is the resource returned by fopen(). Not the filename.
So change the relevant part of your program to this:
$handle = fopen($filename, "w") or die("...");
$content = "foobar";
fwrite($handle, $content);
fclose($handle); // Don't forget to close when you're done.

Need help - php save .txt

I need your help.
I need to every time the code stores the information in txt file, then each new record to the new line and what should be done to all be numbered?
<?php
$txt = "data.txt";
if (isset($_POST['Password'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['Password'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
Added some comments to explain the changes.
<?php
$file = "data.txt"; // check if both fields are set
$fh = fopen($file, 'a+'); //open the file for reading, writing and put the pointer at the end of file.
$word=md5(rand(1,10)); //random word generator for testing
fwrite($fh,$word."\n"); // Write information to the file add a new line to the end of the word.
rewind($fh); //return the pointer to the start of the text file.
$lines = explode("\n",trim(fread($fh, filesize($file)))); // create an array of lines.
foreach($lines as $key=>$line){ // iterate over each line.
echo $key." : ".$line."<br>";
}
fclose($fh); // Close the file
?>
PHP
fopen
fread
explode
You can do like this in a more simpler way..
<?php
$txt = "data.txt";
if (isset($_POST['Password']) && file_exists($txt))
{
file_put_contents($txt,$_POST['Password'],FILE_APPEND);
}
?>
we open file to write into it ,you must make handle to a+ like php doc
So your code will be :
<?php
$fileName = "data.txt"; // change variable name to file name
if (isset($_POST['Password'])) { // check if both fields are set
$file = fopen($fileName, 'a+'); // set handler to a+
$txt=$_POST['Password'];
fwrite($file,$txt); // Write information to the file
fclose($file); // Close the file
}
?>

Developing a text editor with PHP

I've started a small project trying to make an online text editor, it WAS going well until the system started overwriting files and adding spaces in unnecessarily. I have one file called editor.php where all the file loading, saving and editing is done.
So this is the opening/closing for the files:
<?php
if(isset($_POST['new'])){
$filer = substr(md5(microtime()),rand(0,26),6);
$file_create = $filer.".txt";
$handle = fopen("files/".$file_create,"w");
fclose($handle);
header("Location: editor.php?e=".$filer);
}
$file = $_GET['e'];
$file = basename($file);
$filename = "files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
file_put_contents($filename, $_POST['text']);
}
?>
further down the page I have this in a <textarea> tag:
<?php
echo $file_content;
?>
This uses the string from the file_get_contents();
But when I save, nothing happens, in fact it erases the file, when I load a file there are eight spaces but nothing else.
I know there is another way to do this with fopen() and if someone could give me a method to use that, it would be much appreciated.
You have to verify if the $_POST['text'] actually has a content in it.
if(isset($_GET['e'])){
$file = $_GET['e'];
$file = basename($file);
$filename = $_SERVER['DOCUMENT_ROOT']."/files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
if(!empty($_POST['text']) && isset($_POST['text']))
{
$length = strlen($_POST['text']);
if($length > 0)
file_put_contents($filename, trim($_POST['text']));
else
die("No content");
}
}
}
ALso check if the file exists and its writable. You can use chmod,mkdir and file_exists functions.
Have a look at PHP's file modes: http://php.net/manual/en/function.fopen.php
If you are opening all your files using fopen() in w mode then your files are being truncated as they are opened. This is how w mode operates. Try using a+ or c+ modes with fopen().
EDIT
Also, the file_put_contents() will also overwrite file contents unless you sett the FILE_APPEND flag, e.g. file_put_contents($file, $data, FILE_APPEND).

PHP fgets() won't work unless it's implemented with a variable?

I'm writing some code that can read in from a .txt file a display it on a webpage.
I had problems in my initial code, in that it would read in any text and it would erase whatever was in the document.
My original code:
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$line = fgets($input);
fclose($input);
return $line
}
It only started working once I put in a While loop to go through EVERY LINE
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$fullText = ""; //Variable full text
while(!feof($input)){
$line = fgets($input);
$fullText = $fullText . $line;
}
fclose($input);
return $fullText;
}
echo readIn();
Use "file_get_contents" to read an entire file into a variable, and then output in whatever fashion you choose.

Using php, how to insert text without overwriting to the beginning of a text file

I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>

Categories