How can I edit the content of a ini file? - php

I would like to be able to edit a config file for a server application using php. The config file is as follows:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://<full_url_of_relay_including_port>
;allowrelay=0
;allowpublicrelay=0
I would like to edit the line:
streamrelayurl_2=http://<full_url_of_relay_including_port>
and then save the file.
I am currently using:
$data = file_get_contents("sc_serv.conf"); //read the file
$convert = explode("\n", $data); //create array separate by new line
to open the file, but now I dont know how to edit it.

As an alternative, you could just use file() instead. This just loads it up into array form, no need to explode. Then after that, you just loop the elements, if the desired needle is found, overwrite it, the write the file again:
$data = file('sc_serv.conf', FILE_IGNORE_NEW_LINES); // load file into an array
$find = 'streamrelayurl_2='; // needle
$new_value = 'http://www.whateverurl.com'; // new value
foreach($data as &$line) {
if(strpos($line, 'streamrelayurl_2=') !== false) { // if found
$line = $find . $new_value; // overwrite
break; // stop, no need to go further
}
}
file_put_contents('sc_serv.conf', implode("\n", $data)); // compound into string again and write

You can use file() to read the file content to an array, then you can iterate trough the array with foreach() searching with the strstr() function the line that have your URL (in this case is in the var $id_change) and change the value. Then as you found what you needed, you end the foreach() with break. And make your string to save in the file with implode() and save the string to the config file with file_put_content().
See the code:
<?php
$new_url = 'http://www.google.com';
$id_change = 'streamrelayurl_2';
$file = "sc_serv.conf";
$data = file($file); //read the file
foreach($data as $key => $value) {
if(strstr($value, $id_change)) {
$info = $id_change . '=' . $new_url . "\n";
$data[$key] = $info;
break;
}
}
$data = implode("", $data);
file_put_contents($file, $data);
?>
Output:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://www.google.com
;allowrelay=0
;allowpublicrelay=0

Related

How to loop through each line in a file PHP

I am making a redeem key page for educational purposes with PHP just to see what it is capable of. I am storing the keys in a txt file as such:
key1
key2
And so on.
I have tried the following to loop through the txt file, insert the values into and array and work off of there. Here is what I have:
$gkey = $_GET["key"];
$file = fopen("./generatedkeys.txt", "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
foreach ($generatedk as $key){
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
$contents = file_get_contents($file);
$contents = str_replace($key, '', $contents);
file_put_contents($file, $contents);
fclose($file);
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
break;
}
}
The code above however doesn't seem to be working. The key is simply not detected and not removed from generatedkeys.txt. (Not sure if there is any errors since I cannot see any).
Is there any obvious mistakes?
Any help is appreciated. Thank you.
I think this should make the process simpler, using file to read the whole file in one go into an array and then using array_search() to find if the key exists (it returns false if not found, so !== false).
Then if found, it just appends the used key to the other file, unsets the array entry for the key and overwrites the original file...
$gkey = $_GET["key"];
$generatedk = file("./generatedkeys.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ( ($entry = array_search(hash("sha256", $gkey), $generatedk)) !== false ) {
// Add key used, with whatever content you want
file_put_contents("./accs.txt", $gkey.PHP_EOL, FILE_APPEND);
// Remove found key from list in input file
unset($generatedk[$entry]);
// Overwrite input file with adjusted array
file_put_contents("./generatedkeys.txt", implode(PHP_EOL, $generatedk));
}
Your code will make some empty lines when erases key from file.
And you passed return value of fopen() as a parameter of file_get_contents(). the return value is resource on file, but file_get_contents() needs string(file path).
You can check following.
$gkey = $_GET["key"];
$file_path="./generatedkeys.txt";
$file = fopen($file_path, "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
fclose($file);
for($i=0; $i<count($generatedk); $i++){
$key=$generatedk[$i];
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
array_splice($generatedk, $i, 1);
file_put_contents($file_path, implode("\n", $generatedk));
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
fclose($accfile);
break;
}
}
I hope it will be working well.
Thanks.

PHP Replace all values in the third column in a csv file

I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>

Write to file using SplFileObject()

I'm trying to edit a file by line using SplFileObject(). I can choose the line of the file I want to edit. But how do I then write a $string to that line?
Here is my code to get the line:
<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>
How do I insert a string on that line?
Note, I don't want to overwrite the file, I simply want to insert a $string at a given line.
This isn't probably the best solution as it will read the whole file and store it in a string. But since there are no other answers you can use this as your last resource.
$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
$line = $file->fgets();
if($line == 'your_condition'){
$line = 'replace this line';
}
$output .= $line;
}
$file = null;
$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);

PHP write in file in specific location

Imagine I have a TXT file with the following contents:
Hello
How are you
Paris
London
And I want to write beneath Paris, so Paris has the index of 2, and I want to write in 3.
Currently, I have this:
$fileName = 'file.txt';
$lineNumber = 3;
$changeTo = "the changed line\n";
$contents = file($fileName);
$contents[$lineNumber] = $changeTo;
file_put_contents($fileName, implode('',$contents));
But it only modifies the specific line. And I don't want to modify, I want to write a new line and let the others stay where they are.
How can I do this?
Edit: Solved. In a very easy way:
$contents = file($filename);
$contents[2] = $contents[2] . "\n"; // Gives a new line
file_put_contents($filename, implode('',$contents));
$contents = file($filename);
$contents[3] = "Nooooooo!\n";
file_put_contents($filename, implode('',$contents));
You need to parse the contents of the file, place the contents in a new array and when the line number you want comes up, insert the new content into that array. And then save the new contents to a file. Adjusted code below:
$fileName = 'file.txt';
$lineNumber = 3;
$changeTo = "the changed line\n";
$contents = file($fileName);
$new_contents = array();
foreach ($contents as $key => $value) {
$new_contents[] = $value;
if ($key == $lineNumber) {
$new_contents[] = $changeTo;
}
}
file_put_contents($fileName, implode('',$new_contents));

Reading text after a certain character in php

Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>

Categories