Can anyone tell the method to modify/delete the contents of a text file using PHP
Using file_put_contents:
file_put_contents($filename, 'file_content');
If you want to append to the file instead of replacing it's contents use:
file_put_contents($filename, 'append_this', FILE_APPEND);
(file_out_contents is the simpler alternative to using the whole fopen complex.)
By using fopen:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
}
Write "" to a file to delete its contents.
To delete contents line by line use:
$arr = file($fileName);
unset($arr[3]); // 3 is an arbitrary line
then write the file contents. Or are you referring to memory mapped files?
There are number of ways to read files. Large files can be handled very fast using
$fd = fopen ("log.txt", "r"); // you can use w/a switches to write append text
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
you can also use file_get_contents() to read files. its short way of achieving same thing.
to modify or append file you can use
$filePointer = fopen("log.txt", "a");
fputs($filePointer, "Text HERE TO WRITE");
fclose($filePointer);
YOU CAN ALSO LOAD THE FILE INTO ARRAY AND THEN PERFORM SEARCH OPERATION TO DELETE THE SPECIFIC ELEMENTS OF THE ARRAY.
$lines = file('FILE WITH COMPLETE PATH.'); // SINGLE SLASH SHOULD BE DOUBLE SLASH IN THE PATH SOMTHING LIKE C://PATH//TO//FILE.TXT
Above code will load the file in $lines array.
Related
I have a large file "file.txt"
I want to read one specific line from the file, change something and then write that line back into its place in the file.
Being that it is a large file, I do not want to read the entire file during the reading or writing process, I only want to access that one line.
This is what I'm using to retrieve the desired line:
$myLine = 100;
$file = new SplFileObject('file.txt');
$file->seek($myLine-1);
$oldline = $file->current();
$newline=str_replace('a','b',$oldline);
Now how do I write this $newline to replace the old line in the file?
You could use this function:
function injectData($file, $data, $position) {
$temp = fopen('php://temp', "rw+");
$fd = fopen($file, 'r+b');
fseek($fd, $position);
stream_copy_to_stream($fd, $temp); // copy end
fseek($fd, $position); // seek back
fwrite($fd, $data); // write data
rewind($temp);
stream_copy_to_stream($temp, $fd); // stich end on again
fclose($temp);
fclose($fd);
}
I got it from: PHP what is the best way to write data to middle of file without rewriting file
I am trying to write to a file and then read the data from the same file. But sometimes I am facing this issue that the file reading process is getting started even before the file writing gets finished. How can I solve this issue ? How can i make file writing process finish before moving ahead?
// writing to file
$string= <12 kb of specific data which i need>;
$filename.="/ttc/";
$filename.="datasave.html";
if($fp = fopen($filename, 'w'))
{
fwrite($fp, $string);
fclose($fp);
}
// writing to the file
$handle = fopen($filename, "r") ;
$datatnc = fread($handle, filesize($filename));
$datatnc = addslashes($datatnc);
fclose($handle);
The reason it does not work is because when you are done writing a string to the file the file pointer points to the end of the file so later when you try to read the same file with the same file pointer there is nothing more to read. All you have to do is rewind the pointer to the beginning of the file. Here is an example:
<?php
$fileName = 'test_file';
$savePath = "tmp/tests/" . $fileName;
//create file pointer handle
$fp = fopen($savePath, 'r+');
fwrite($fp, "Writing and Reading with same fopen handle!");
//Now rewind file pointer to start reading
rewind($fp);
//this will output "Writing and Reading with same fopen handle!"
echo fread($fp, filesize($savePath));
fclose($fp);
?>
Here is more info on the rewind() method http://php.net/manual/en/function.rewind.php
I have mentioned the URL through which i got the solution. I implemented the same. If you want me to copy the text from that link then here it is :
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
// release lock
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
Use fclose after writing to close the file pointer and then fopen again to open it.
I have the following script to write a file that i grabbed from online.
$newfname = $data['transferPath'] . '/' . $data['filename'];
$file = fopen ($data['filePath'], "rb");
if(!$file) {
throw new Exception('Unable to open file for reading ' . $file);
}
if($file) {
$newf = fopen ($newfname, "wb");
if(!$newf) {
throw new Exception("Cant open file for writing");
}
if($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
}
if($file) {
fclose($file);
}
if($newf) {
fclose($newf);
}
when i post the data and run this script I keep getting the exception for cant open file for writing because there already is a file but that name in the same directory. Im trying to overwrite the file with the new file any ideas what i can do. iv tried using the options for fopen using w and w+. I need to completely overwrite the file there if exists otherwise create the file.
Try using the a+ ending parameter to the fopen() function.
Look here for a complete list of the possible parameters and what they do to find the right one for your purpose!
If none of these satisfy your needs then you could do something like this:
$fopen($data['filePath'], "r");
if($file){
unlink($data['filePath']);
}
Then after it deletes the file, if it's there, then just do another fopen with the w parameter.
below is the code which i want to modify
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()){
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
I want to save the contents into the memory and transfer it accross to other server without saving it on apache server.
when i try to output the contents i only see resource id# 5. Any suggestion, comments are highly apprecited . thanks
The code you have opens file handles, which in themselves are not the content. To get the content into a variable, just read it like any other file:
$put = file_get_contents('php://input');
To get the contents of the stream:
rewind($temp); // rewind the stream to the beginning
$contents = stream_get_contents($temp);
var_dump($contents);
Or, use file_get_contents as #deceze mentions.
UPDATE
I noticed you're also opening a temp file on disk. You might want to consider simplifying your code like so:
$put = stream_get_contents(STDIN); // STDIN is an open handle to php://input
if ($put) {
$target = fopen('/storage/put.txt', "w");
fwrite($target, $put);
fclose($target);
}
I need to scan through a 30MB text file - it's a list of world cities - How can I access this file, I feel like a File_Get_Contents will give my server a stroke
Just fopen it and then use fgets.
Filesystem functions come handy in this situation.
Example
$filename = "your_file_path";
// to open file
$fp = fopen($filename, 'r'); // use 'rw' to open file in read/write mode
// to output entire file
echo fread($fp, filesize($filename));
// to close file
fclose($fp);
References
(some handy functions)
All Filesystem Functions
fopen() - open file
fread() - read file content
fgets() - to get line
fwrite() - write content to file
fseek() - change file pointer's position
rewind() - rewind file pointer to pos 0
fclose() - close file
...
<?php
$fh = #fopen("inputfile.txt", "r");
if ($fh) {
while (($line = fgets($fh)) !== false) {
echo $line;
// do something with $line..
}
fclose($fh);
}
?>
More information/examples on http://pt.php.net/manual/en/function.fgets.php