Search code examples
phpfopenfile-put-contents

PHP: file_put_contents and writing to multiple files in a for loop not working


For some background I have a bit of code that I am using to generate html files that contain a link to a unique code. Ultimately this ends up on a USB drive thats distributed to customers. This is done in batch so i can create as many custom files with code as needed.

if ( !empty($_POST) ) {

$url = trim($_POST['url']);

$codes = trim($_POST['codes']);

$codes_array = explode("\n", $codes);

$codes_array = array_filter($codes_array, 'trim');

foreach ($codes_array as $code) {

    $html = <<<EOD
<html>
<head></head>
<body>
<a href="$url$code">Download Now</a>
</body>
</html>
EOD;

    file_put_contents("codes/".$code.".html",$html);

}

}

What happens is only one file is generated in that folder, but its name is always the last element in the array, the other files don't get generated, it seems like the files getting overwritten even though $code is different on each iteration.

I tried the following code as well with same results.

$fh = fopen("codes/".$code.".html", "w+");
fwrite($fh, $html);
fclose($fh); 

Any ideas?


Solution

  • Replace

    $codes_array = array_filter($codes_array, 'trim');
    

    with

    $codes_array = array_map('trim', $codes_array);
    

    Otherwise, only the last element will not have \n at the end.