You can use file_get_contents() to get the original data first, then prepend your string to that:
$existing = file_get_contents('/path/to/file.txt');
$fp = fopen('/path/to/file.txt', 'w');
$myString = 'hello world'. PHP_EOL;
fwrite($fp, $myString. $existing);
fclose($fp);
here we open the file with w - to fully overwrite, not append. Because of this, we need to get the file contents before the fopen().
Then we get the existing file contents and concat it to your string, and overwrite the file.
Edit: file_put_contents() - as suggested by Nigel Ren
$existing = file_get_contents('/path/to/file.txt');
$myString = 'hello world'. PHP_EOL;
file_put_contents('/path/to/file.txt', $myString. $existing);
Edit: function to create one-liner
function prepend_to_file(string $file, string $data)
{
if (file_exists($file)) {
try {
file_put_contents($file, $data. file_get_contents($file));
return true;
} catch (Exception $e) {
throw new Exception($file. ' couldn\'t be amended, see error: '. $e->getMessage());
}
} else {
throw new Exception($file. ' wasn\'t found. Ensure it exists');
}
}
# then use:
if (prepend_to_file('/path/to/file.txt', 'hello world')) {
echo 'prepended!';
}