user1062058
user1062058

Reputation: 275

Lightweight fopen technique in PHP

I'm trying to write data to a simple txt file in PHP and open it so the user can download it. I'd like to keep it very lightweight, when I run this I get:

Warning: fopen(testFile.txt) [function.fopen]: failed to open stream: File exists in /home/user/script.php on line 9

Here is my sample code:

<?php

$File = "sample.txt";
$write = fopen($File, 'w') or die();
$stringData = "asdfjkl;";
fwrite($write, $stringData);
fclose($write);

$open = fopen($File, 'x') or die();
fclose($open);

?> 

Thank you!

Upvotes: 0

Views: 242

Answers (1)

Paul
Paul

Reputation: 141839

Use file_put_contents to write to the file:

$filename = "sample.txt";
$stringData = "asdfjkl;";
file_put_contents($filename, $stringData);

Then when you want to output the contents of the file use:

$filename = "sample.txt";
readfile($filename);

If you want the file contents to be returned as a string instead of output immediately use file_get_contents instead of readfile

Upvotes: 1

Related Questions