Jump to content


Photo

writing to and reading from a file in one script


  • Please log in to reply
2 replies to this topic

#1 juanc

juanc
  • Members
  • PipPip
  • Member
  • 16 posts

Posted 03 August 2006 - 11:11 PM

Hi there

can someone help me here. I'm trying create the same process as on this forum where you can preview the post. Basically I want the contents of a form's textarea to be written to a text file and then output the text file's content to the browser. Below is the code I've used, it works fine as far as writing to the file goes but it doesn't read out to the browser ....ie. echo $data doesn't work. Have I missed something obvious?


$file = "../scratchpad/" . $_POST['theID'] . "/scratchpad.txt";
$fh = fopen($file, "w+");

if($_POST['submit'])
  {
    fwrite($fh, $_POST['code']);
	// please not that $_POST['theID'], $_POST['submit'] and $_POST['code'] have all come from a form on another page	
	$data = fread($fh,filesize($file));
	echo $data; 
	echo "<br /><br />";	
	echo "<form action=$_SERVER[PHP_SELF] method=post>";
	echo "<textarea name=code rows=10 cols=50 wrap=virtual>$_POST[code]</textarea><br />";
	echo "<input type=hidden name=theID value=$_POST[theID] />";
	echo "<input type=submit name=submit_update value='Send to scratchpad' />";
	echo "</form>";		
   }
else if(($_POST['submit_update']) or ($_POST['submit_update2']))
   {    
	fwrite($fh, $_POST['code']);
	$data = fread($fh,filesize($file));
	echo $data; 
	echo "<br /><br />";	
	echo "<form action=$_SERVER[PHP_SELF] method=post>";
	echo "<textarea name=code rows=10 cols=50 wrap=virtual>$_POST[code]</textarea><br />";
	echo "<input type=hidden name=theID value=$_POST[theID] />";
	echo "<input type=submit name=submit_update2 value='Send to scratchpad' />";
	echo "</form>";	   
   }
   
fclose($fh);


[/code][/code]


#2 sk93

sk93
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 03 August 2006 - 11:20 PM

Hi.

May not be the right answer, but it's my understanding of what's written in the manual :)

try changing this line:
$fh = fopen($file, "w+");

to this:
$fh = fopen($file, "r+");

I think this may be the cause of your issue because of the definition of "w+" states:

'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.


And the "truncate the file to zero length" bit is likely to be returning you an empty string...

wheras "r+" only has the following definition:

'r+' Open for reading and writing; place the file pointer at the beginning of the file. 


Hope it works!

Cheers,
Sk93

#3 hitman6003

hitman6003
  • Members
  • PipPipPip
  • Advanced Member
  • 1,807 posts

Posted 04 August 2006 - 01:54 AM

write to the file, then close it, then read the contents.

fwrite($fh, $_POST['code']);
fclose($fh);
$data = file_get_contents($file);
echo $data;





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users