How do I prepend file to beginning?
The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
Writing TXT file in PHP, want to insert the new line in the beginning
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!';
}
Using php, how to insert text without overwriting to the beginning of a text file
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+
rather than r+
)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents
) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents
. In this case, consider using rewind($file)
, which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind()
, not to open the file with the a
(or a+
) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
How to add new data to the top of .txt without deleting in PHP
$txt = "col1 col2 col3 coln";
file_put_contents('data.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
Please, try this. Thanks
PHP writing a text file in the begin
Check the fopen
manual on modes: http://www.php.net/manual/en/function.fopen.php
Try 'r+' Open for reading and writing; place the file pointer at the beginning of the file.
Altough without any code this is hard to answer.
Create or write/append in text file
Try something like this:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
How to write a text file line by line in PHP?
Just change your code:
if( isset($_POST['submit']) ){
$name = $_POST['name'];
$age = $_POST['age'];
$address = $_POST['address'];
$file = fopen("student.txt","a");
fwrite($file,$name.PHP_EOL);
fwrite($file,$age.PHP_EOL);
fwrite($file,$address.PHP_EOL);
fclose($file);
echo "Adding student successfully";
}
I hope it works for you. :)
Related Topics
How to Round Up a Number to Nearest 10
How to Get Code Point Number For a Given Character in a Utf-8 String
Can't Connect to Https Site Using Curl. Returns 0 Length Content Instead. What How to Do
How to Run a PHP File in a Scheduled Task (Windows Task Scheduler)
Remove Script Tag from HTML Content
PHP Domdocument Failing to Handle Utf-8 Characters (☆)
How to Validate Domain Name in PHP
Opening/Closing Tags & Performance
PHP Sort Array by Two Field Values
Connect to SQL Server Through Pdo Using SQL Server Driver
How to Replace Special Characters With the Ones They'Re Based on in PHP
Http Headers For File Downloads