I have the following scenarion.
Everytime my page loads I create a file. Now my file has two tags within. {theme}{/theme} and {layout}{/layout}, now everytime I choose a certain layout or theme it should replace the tags with {layout}layout{/layout} and {theme}theme{/theme}
My issue is that after I run the following code
if(!file_exists($_SESSION['file'])){
$fh = fopen($_SESSION['file'],"w");
fwrite($fh,"{theme}{/theme}\n");
fwrite($fh,"{layout}{/layout}");
fclose($fh);
}
$handle = fopen($_SESSION['file'],'r+');
if ($_REQUEST[theme]) {
$theme = ($_REQUEST[theme]);
//Replacing the theme bracket in the cache file for rememberence
while($line=fgets($handle)){
$line = preg_replace("/{theme}.*{\/theme}/","{theme}".$theme."{/theme}",$line);
fwrite($handle, $line);
}
}
My output looks as follows
{theme}{/theme}
{theme}green{/theme}
And it needs to look like this
{theme}green{/theme}
{layout}layout1{/layout}
I rarely use random-access file operation but like to read it all as text and write ti back so I might be wrong here. BUT as I can see, you read the first line (so the pointer is at the beginning of the second line). Then you write '{theme}green{/theme}' into that file so it replaces the next position text (the second line).
In this case (as your data is small), you better get the hold file. Change it as string and write it back.
Related
I'm using php to perform read/write operation in a txt file. Currently I am using fseek($file,0) and if I am using "a" mode with fopen() it add the text at last and if I'm using "c" or "rw+" mode then it replace the string at the beginning of text file. If I increase the position number suppose to 10 then it leave the first 10 character and after that add string by replacing the existing text in file.
What I want to achieve is, not to overwrite the text in the file, just append at that position.
And is there any way in which, I append the text not by giving position number, just search the specific keyword in the file and append the text at that position.
abc.php
<?php
$val = "string";
echo $val;
$myfile = fopen("demo.txt", "c") or die("Unable to open file!");
fseek($myfile, 0);
fwrite($myfile, $val);
fclose($myfile);
?>
demo.txt
this is some text
this is some text
this is some text
$all = file_get_contents("file");
$find = strpos($all, "needle");
$write = substr($all, 0, $find) . "insert" . substr($all, $find);
file_put_contents("file", $all);
The way filesystems work is that you cannot insert bytes in the middle. You need to overwrite all the contents behind if you have to insert something in the middle.
If the performance impacts do not suit your needs, you might want to use a database format to save data.
Or if you don't want to learn to use a database, a "convenient" way is to adding padding bytes between units in the file so that you can overwrite those padding bytes without having to move the bytes behind. This is actually how most implementations of filesystems and databases prevent overhead when inserting in the middle is needed.
I have a text file. I want to delete some lines with a query of search.
The array is line by line. I want to made it like http://keywordshitter.com/
The logic is,
SEARCH --> IN ARRAY --> OUTPUT IS ARRAY WITHOUT "QUERY OF SEARCH"
Code I have tried:
$fileset = file_get_contents("file.txt");
$line = explode("\n", $fileset);
$content = array_search("query",$line);
print_r($content);
MY file.txt
one
two
three
apple
map
I have used array_search but not working.
you can do search like
$fileset=file("file.txt"); // file function reads entire file into an array
$len=count($fileset);
for($i=0;$i<$len;$i++)
{
if($fileset[$i]=="query")
{
$fileset[$i]="";
break; //then we will stop searching
}
}
$fileset_improve=implode($fileset); //this will again implode your file
$handle=fopen("file.txt","w"); //opening your file in write mode
fwrite($handle,$fileset_improve); //writing file with improved lines
fclose($handle); //closing the opened file
remember this lines will make your search line blank....
if you wanna then you can arrange whole array i.e. shifting following indexed data to previous index to decrease line counts but this will increase your programming complexity.
Hope this will work for you.
Thanks
Use PHP_EOL on your explode function instead of "\n". PHP_EOL will handle the correct line break character(s) of the server platform.
I'm looking to read contents of a file between two tags in a large text file (so can't read the whole file at once due to memory restrictions on my server provider). This file has around 500000 lines of text.
This ( PHP: Read Specific Line From File ) isn't an option (I don't think), as the text I need to read varies in length and will take up multiple lines (varies from 20-5000 lines).
I am planning to use fopen, fread (read only) and fclose to read the file contents. I have experience of using these functions already.
I am looking to read all the contents in a selected part of the file. i.e.
File contents example
<<TAGNAME-1>>AAAA AAAA AAAA<<//TAGNAME-1>>
<<TAGNAME-2>>TEXT TEXT TEXT<<//TAGNAME-2>>
To select the text "AAAA AAAA AAAA" between the <<TAGNAME-1>> and <<//TAGNAME-1>> when TAGNAME-1 is called as a variable in my script.
How could I go about selecting all the text between the two tags that I require? (and ignore the remainder of the file) I have the ability to create the two tags where required in my php script - my issue is implementing this within the fread function.
You could grep the text file which would only return the text with a matching tag.
$tagnum = 2; //variable
$pattern = "<<TAGNAME-";
$searchstr = $pattern.$tagnum; //concat the prefix with the tag number
$fpath ="testtext.txt"; //define path to text file
$result = exec('grep -in "'.$searchstr.'" '.$fpath);
echo $result;
Where $tagnum would define each tag to search. I've tested it in my sandbox and it works as expected. Note this will read the whole line until the end tad or newline is reached.
Regards,
I want to make a .php file downloadable by my users.
Every file is different from an user to another:
at the line #20 I define a variable equal to the user ID.
To do so I tried this: Copy the original file. Read it until line 19 (fgets) then fputs a PHP line, and then offer the file to download.
Problem is, the line is not inserted after line 19 but at the end of the .php file. Here is the code:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a+')) {
echo "Cannot open file ($filename)";
exit;
}
for ($i = 1; $i <= 19; $i++) {
$offset = fgets($handle);
}
if (fwrite($handle, $somecontent) === FALSE) {
exit;
}
fclose($handle);
}
What would you do ?
append mode +a in fopen() places the handle's pointer at the end of the file. Your fgets() loop will fail as there's nothing left to read at the end of the file. You're basically doing 19 no-ops. Your fwrite will then output your new value at the end of the file, as expected.
To do your insert, you'd need to rewind() the handle to the beginning, then do your fgets() loop.
However, if you're just wanting people to get this modified file, why bother doing the "open file, scan through, write change, serve up file"? This'd leave a multitude of near-duplicates on your system. A better method would be to split your file into two parts, and then you could do a simple:
readfile('first_part.txt');
echo "The value you want to insert";
readfile('last_part.txt');
which saves you having to save the 'new' file each time. This would also allow arbitrary length inserts. Your fwrite method could potentially trash later parts of the file. e.g. You scan to offset "10" and write out 4 bytes, which replaces the original 4 bytes at that location in the original file. At some point, maybe it turns into 5 bytes of output, and now you've trashed a byte in the original and maybe have a corrupted file.
The a+ mode means:
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
You probably want r+
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
Put your desired code in one string variable. Where you will have %s at point where you want to customize your code. After that just respond with php MIME type.
eg;
$phpCode = "if (foo == blah) { lala lala + 4; %s = 5; }", $user_specific_variable;
header('Content-type: text/php');
echo $phpCode;
Voila.
NB: Maybe mime type is not correct, I am talking out of my ass here.
I think instead of opening the file in "a+" mode, you should open the file in "r+" mode, because "a" always appends to the file. But I think the write will anyways overwrite your current data. So, the idea is that you'll need to buffer the file, from the point where you intend to write to the EOF. Then add your line followed by what you had buffered.
Another approach might be to keep some pattern in your PHP file, like ######. You can then:
1. copy the original PHP script
2. read the complete PHP script into a single variable, say $fileContent, using file_get_contents()
3. use str_replace() function to replace ###### in $fileContent with desired User ID
4. open the copied PHP script in "a" mode and rewrite $fileContent to it.
The following code supposed to add at the beginning of my php files on the webserver the string abcdef.
However it replaces all the content with the abcdef. How can I correct it?
Also how can I add something on the end instead of the beginning?
foreach (glob("*.php") as $file) {
$fh = fopen($file, 'c'); //Open file for writing, place pointer at start of file.
fwrite($fh, 'abcdef');
fclose($fh);
}
You just need to open the file with a flag that allows you to write without truncating the file to zero length:
$fh = fopen($file, 'r+');
However it replaces all the content with the abcdef. How can I correct it?
From the documentation for fopen on the "c" mode:
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file.
When you write 'abcdef' to the file, it will overwrite the first six characters. To prepend text, you'll need to copy the existing content, either by reading it out before writing the additional text, or by:
creating a new file,
writing the new text,
then copying over the old content,
then removing the old file and
renaming the new.
Also how can I add something on the end instead of the begining?
Use the append mode: "a".