Search code examples
phpfile-iofwrite

PHP fwrite writing empty file


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


Solution

  • 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.