What are the differences between using popen and other file writing functions like fopen or file_put_contents in PHP?

When writing to files in PHP, using popen can be useful when you need to execute a command and write its output directly to a file. This is different from using functions like fopen or file_put_contents, which are typically used for directly writing data to a file without executing external commands. If you need to run a command and capture its output in a file, popen is the way to go.

$command = 'ls -la'; // Example command to list files
$file = fopen('output.txt', 'w');
$handle = popen($command, 'r');
while (!feof($handle)) {
    fwrite($file, fread($handle, 8192));
}
pclose($handle);
fclose($file);