0

I'm trying to make this save a file and it creates the file, but it's always empty. This is the code for it:

<?php

$code = htmlentities($_POST['code']);

$i = 0;
$path = 'files/';
$file_name = '';

while(true) {
    if (file_exists($path . strval($i) . '.txt')) {
        $i++;
    } else {
        $name = strval($i);
        $file_name = $path . $name . '.txt';
        break;
    }
}

fopen($file_name, 'w');
fwrite($file_name, $code);
fclose($file_name);

header("location: index.php?file=$i");

?>

I echoed out $code to make sure it wasn't empty, and it wasn't. I also tried replacing

fwrite($file_name, $code);

with this:

fwrite($file_name, 'Test');

and it was still empty. I have written to files a couple of times before in PHP, but I'm still really new to PHP and I have no idea whats wrong. Could someone tell me what I'm doing wrong or how to fix this? Thanks

Addison
  • 3,791
  • 3
  • 28
  • 48

2 Answers2

1

Take a look of the samples on php.net

George Sharvadze
  • 560
  • 9
  • 25
1

Reading/Writing to/from a file or stream requires a resource handle:

$resource = fopen($file_name, 'w');
fwrite($resource, $code);
fclose($resource);

The resource handle $resource is essentially a pointer to the open file/stream resource. You interact with the created resource handle, not the string representation of the file name.

This concept also exists with cURL as well. This is a common practice in PHP, especially since PHP didn't have support for OOP when these methods came to be.

zamnuts
  • 9,492
  • 3
  • 39
  • 46