How to update an ini file with php? - php

I have an existing ini file that I have created and I would like to know if there was a way to update a section of the file or do I have have to rewrite the entire file each time?
Here is an example of my config.ini file:
[config]
title='test'
status=0
[positions]
top=true
sidebar=true
content=true
footer=false
Say I want to change the [positions] top=false. So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file. Or is there a way just to change that section?

I used the first suggestion of you:
So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file
function config_set($config_file, $section, $key, $value) {
$config_data = parse_ini_file($config_file, true);
$config_data[$section][$key] = $value;
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($config_file, $new_content);
}

If you use the PHP INI functions, you must rewrite the file each time.
If you write your own processor, you could (with limitations) update in place. If your insertions are longer or shorter than your deletions, you'll have to rewrite the file anyhow.

This is a perfect example of when you could use regular expressions to replace a string of text. Check out the preg_replace function. If you're not quite sure how to use regular expressions you can find a great tutorial here
Just to clarify you'll need to do something like this:
<?php
$contents = file_get_contents("your file name");
$contents = preg_replace($pattern, $replacement, $contents);
$fh = fopen("your file name", "w");
fwrite($fh, $contents);
?>
Where $pattern is your regex to match and $replacement is your replacement value.

Related

How to format I/O data from script

I was using a script to exclude a list of words from another list of keywords. I would like to change the format of the output. (I found the script on this website and I have made some modification.)
Example:
Phrase from outcome: my word
I would like to add quotes: "my word"
I was thinking that I should put the outcome in new-file.txt and after to rewrite it, but I do not understand how to capture the result. Please, kindly give me some tips. It's my first script :)
Here is the code:
<?php
$myfile = fopen("newfile1.txt", "w") or die("Unable to open file!");
// Open a file to write the changes - test
$file = file_get_contents("test-action-write-a-doc-small.txt");
// In small.txt there are words that will be excluded from the big list
$searchstrings = file_get_contents("test-action-write-a-doc-full.txt");
// From this list the script is excluding the words that are in small.txt
$breakstrings = explode(',',$searchstrings);
foreach ($breakstrings as $values){
if(!strpos($file, $values)) {
echo $values." = Not found;\n";
}
else {
echo $values." = Found; \n";
}
}
echo "<h1>Outcome:</h1>";
foreach ($breakstrings as $values){
if(!strpos($file, $values)) {
echo $values."\n";
}
}
fwrite($myfile, $values); // write the result in newfile1.txt - test
// a loop is missing?
fclose($myfile); // close newfile1.txt - test
?>
There is also a little mistake in the script. It works fine however before entering the list of words in test-action-write-a-doc-full.txt and in test-action-write-a-doc-small.txt I have to put a break for the first line otherwise it does not find the first word.
Example:
In test-action-write-a-doc-small.txt words:
pick, lol, file, cool,
In test-action-write-a-doc-full.txt wwords:
pick, bad, computer, lol, break, file.
Outcome:
Pick = Not found -- here is the mistake.
It happens if I do not put a break for the first line in .txt
lol = Found
file = Found
Thanks in advance for any help! :)
You can collect the accepted words in an array, and then glue all those array elements into one text, which you then write to the file. Like this:
echo "<h1>Outcome:</h1>";
// Build an array with accepted words
$keepWords = array();
foreach ($breakstrings as $values){
// remove white space surrounding word
$values = trim($values);
// compare with false, and skip empty strings
if ($values !== "" and false === strpos($file, $values)) {
// Add word to end of array, you can add quotes if you want
$keepWords[] = '"' . $values . '"';
}
}
// Glue all words together with commas
$keepText = implode(",", $keepWords);
// Write that to file
fwrite($myfile, $keepText);
Note that you should not write !strpos(..) but false === strpos(..) as explained in the docs.
Note also that this method of searching in $file will maybe give unexpected results. For instance, if you have "misery" in your $file string then the word "is" (if separated by commas in the original file) will be refused, as it is found in $file. You might want to review this.
Concerning the second problem
The fact that it does not work without first adding a line-break in your file leads me to think it is related to the Byte-Order Mark (BOM) that appears in the beginning of many UTF-8 encoded files. The problem and possible solutions are discussed here and elsewhere.
If indeed it is this problem, there are two solutions I would propose:
Use your text editor to save the file as UTF-8, but without BOM. For instance, notepad++ has this possibility in the encoding menu.
Or, add this to your code:
function removeBOM($str = "") {
if (substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
$str = substr($str, 3);
}
return $str;
}
and then wrap all your file_get_contents calls with that function, like this:
$file = removeBOM(file_get_contents("test-action-write-a-doc-small.txt"));
// In small.txt there are words that will be excluded from the big list
$searchstrings = removeBOM(file_get_contents("test-action-write-a-doc-full.txt"));
// From this list the script is excluding the words that are in small.txt
This will strip these funny bytes from the start of the string taken from the file.

PHP Validate Value $_GET from url against lines of a txt file

i have a problem i couldn't figure out since im self-taught and still exploring the php world
so i have a text file that looks like this:
951753159
456787541
123156488
748651651
and i got an url with a variable
http://example.com/mypage.php?variable=951753159
what i want is to check if the url variable matches one of the txt file lines in order to execute a code
i already tried this
$search = $_GET["variable"];
$file = "variables.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
THE CODE THAT I WANT TO EXECUTE
}
but for some reason it matches the whole content of the file
any help is highly appreciated
Thanks in advance :)
Try with an array from file():
$lines = file("variables.txt", FILE_IGNORE_NEW_LINES);
if(in_array($_GET["variable"], $lines)) {
// YES FOUND
} else {
// NOT FOUND
}
From the documentation on `file_get_contents', the entire contents of the file are read as a string. So that is why it is matching against the entire file.
The command that you want to use is file, this reads the file into an array of each line.
I would
Use file to read the file into an array.
Then array_flip the array so that it's values are now the keys
Which allows me to isset($array[$key])
You can do this.
<?php
#$search = $_GET["variable"];
$search = '123156488';
$file_txt = "content.txt";
$file = file($file_txt);//convert the txt in array
foreach ($file as $key => $value) {
if (trim($search) == trim($value)) {
print "DO something! " . $value;
}
}?>
Regards.
Nelson.

How do you read the entire text file inside a paint" ";?

First time I ask a question here and sorry for my english. So, here's my code:
function data1_show() {
$f = fopen("data/data1.txt", "r");
while (feof($f)!=true) {
$line = fgets($f);
print $line."<br>";
}
fclose($f);
print "<div id=\"s1\" class=\"s\"> </div>";
}
Not the best, but it works at least. But I want to read the text file inside the print "div /div", and this is the problem. I've tried several reading methods and none of them worked. I just can't figure it out.
You can do explode:
$array = explode('div', $text_data);
and then use $array and proper element of it that you want.
You can also use RegExp:
preg_match("/^div([a-zA-Z0-9_-\.\+\-]).*//div$/, $content, $res);
The regexp is better I haven't tested that.

issue using file_get_contents with a variable as the link to target file

I'm trying to loop through an array of links, and use the file_get_contents to get the source code and take certain content from it:
$links = file('mysite2.txt');
foreach($links as $link) {
$f = file_get_contents("$link");
$source = $f;
if(preg_match('/<meta pro=\"(.*)\" \/>/',$source,$matches)) {
$answer = $matches[1];
echo "$answer";
}
}
Now when i use $link in the file_get_contents (file_get_contents("$link")) function, the preg_match condition is false. Yet when i use one of the links in my_site2.txt in the file_get_contents (`file_get_contents("http://www.site.com/something")) it works fine.
I've even tried using a different txt file which only contains one link, which had the correct string in the source code.
Iv also tried without quotes: file_get_contents($link)
There were a couple of things.
filenames in $f will contain newlines. You need to add an additional flag for file to prevent this:
$links = file('mysite2.txt', FILE_IGNORE_NEW_LINES);
you don't need to escape double quotes in your regex.
are you sure that your regex needs a space before />? Your regex will match <meta pro="test" /> but not <meta pro="test"/>.
The contents of $link when decalred in the foreach loop is probably an array or an object.
Try var_dump() on $link and see what is within it, this might help you to understand how to manipulate it's contents.
How is you .txt file setup?
Heres a solution:-
If you just sepreate the links like
link1,link2,link3,link4,link5
Then do
$links = explode( ',' , file_get_content($file) ) ;
Then foreach for this array
Simply remove the quotes from $f = file_get_contents("$link");
to make $f = file_get_contents($link);

Inserting something at a particular line in a text file using PHP

I have a file called config.php, I want it to remain exactly as is, however on Line # 4 there is a line saying:
$config['url'] = '...could be anything here';
I'd like to only replace the contents of line # 4 with my own url provided for $config['ur'], is there a way to do this in PHP?
Since you know the exact line number, probably the most accurate way to do this is to use file(), which returns an array of lines:
$contents = file('config.php');
$contents[3] = '$config[\'url\'] = "whateva"'."\n";
$outfile = fopen('config.php','w');
fwrite($outfile,implode('',$contents));
fclose($outfile);
$myline = "my confg line";
$file = "config.php";
$contents = file($file);
$contents[3] = $myLine;
$file = implode("\n", $contents);
Either create another config (myconfig.php). Include the original and overwrite the option. include myconfig.php instead of the original one.
OR
Go to where config is included (you did use a single place for all your includes right?) and set the config option there.
include "config.php"
$config['url'] = "my_leet_urlz";
you could read the file, use str_replace or preg_replace on the appropriate strings, then write the file back to itself.
$filename = "/path/to/file/filename";
$configFile = file($filename);
$configFile[3] = '$'."config['url'] = '...could be anything here';";
file_put_contents($filename ,$configFile);
If there is only one $config['url'], use a preg_replace()
http://us.php.net/preg_replace
something like:
$pattern = '\$config['url'] = "[\d\w\s]*"'
$file_contents = preg_replace($pattern, $config['url'] = "my_leet_urlz";,$file_contents);
you'll need to fix the pattern as I'm new at regex and I know that's not right.

Categories