Files and Streams
Write File
file_put_contents writes a string and reports how many bytes were written.
write
For small text files, a single function call is enough to write content.
Write File
write_file.php
Replay: real traced execution (multi-file project)
<?php
$text = "alpha";
$file = "php_write_file.txt";
$bytes = file_put_contents($file, $text);
$written = $bytes === false ? 0 : $bytes;
unlink($file);
echo "text=" . $text . "\n";
echo "written=" . $written . "\n";
<?php
$text = "beta";
$file = "php_write_file.txt";
$bytes = file_put_contents($file, $text);
$written = $bytes === false ? 0 : $bytes;
unlink($file);
echo "text=" . $text . "\n";
echo "written=" . $written . "\n";
<?php
$text = "gamma";
$file = "php_write_file.txt";
$bytes = file_put_contents($file, $text);
$written = $bytes === false ? 0 : $bytes;
unlink($file);
echo "text=" . $text . "\n";
echo "written=" . $written . "\n";
$text ← alpha, $file ← php_write_file.txt, $bytes ← 5, $written ← 5
1<?php2$text→ alpha = "alpha"; //@text="beta", "gamma"3$file→ php_write_file.txt = "php_write_file.txt";45$bytes→ 5 = file_put_contents($filephp_write_file.txt, $textalpha);6$written→ 5 = $bytes5 === false ? 0 : $bytes;7unlink($filephp_write_file.txt);89echo "text=" . $textalpha . "\n";10echo "written=" . $written5 . "\n";outputtext=alpha written=5
$text ← beta, $file ← php_write_file.txt, $bytes ← 4, $written ← 4
1<?php2$text→ beta = "beta";3$file→ php_write_file.txt = "php_write_file.txt";45$bytes→ 4 = file_put_contents($filephp_write_file.txt, $textbeta);6$written→ 4 = $bytes4 === false ? 0 : $bytes;7unlink($filephp_write_file.txt);89echo "text=" . $textbeta . "\n";10echo "written=" . $written4 . "\n";outputtext=beta written=4
$text ← gamma, $file ← php_write_file.txt, $bytes ← 5, $written ← 5
1<?php2$text→ gamma = "gamma";3$file→ php_write_file.txt = "php_write_file.txt";45$bytes→ 5 = file_put_contents($filephp_write_file.txt, $textgamma);6$written→ 5 = $bytes5 === false ? 0 : $bytes;7unlink($filephp_write_file.txt);89echo "text=" . $textgamma . "\n";10echo "written=" . $written5 . "\n";outputtext=gamma written=5