Inserting something at a particular line in a text file using PHP - 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.

Related

PHP How to get the "file_put_contents" to work?

Im very new to programming and this is the first time i use PHP.
Im working on a webpage to switch 433mhz relays and show their current state.
But to know which switch is on or off you need to remember it when the button is clicked. So i thought of a States.txt file and update a line from 0 to 1. (or from 1 to 0)
I can already read a specific line, but when i try to write on a specific rule using "file_put_contents" it reads the line, and writes to a new file called like the rule.
$file = "States.txt";
$lines = file($file);
$btn1 = $lines[0];
$btn2 = $lines[1];
$btn3 = $lines[2];
$btn4 = $lines[3];
$btn5 = $lines[4];
$btn6 = $lines[5];
//file_put_contents($file, "test123");
file_put_contents( $lines[2] , "test123");
It should overwrite the specified rule, but instead it reads the line, and creates a new file called like the content of that line.
$file = "States.txt";
$lines = file($file);
$lines[2] = 'NEW VALUE' . PHP_EOL;
file_put_contents($file, $lines);

how to replace a string inside files using php

I intend to create a simple codes using php that can replace strings inside the files much like replace function in the notepad and ms word but the difference is it will replace all strings match to the desired string to change in all files inside the folder any Idea how to do that?
You can use useful glob() php function.
Example
<?php
$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');
foreach(glob('c:\wamp\www\FindReplace\*') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("Hello","World",$file_contents);
file_put_contents($path_to_file,$file_contents);
}
?>
If You have sub folders in your directory then you can get files with the below code
$path = realpath(__DIR__ . '/textfiles/'); // Path to your textfiles
$files_in_your_folder = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);

How can I add variable names to the end of a file?

I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);

How to remove a particular part of a string in a JavaScript file

Using PHP, I want to be able to open a JavaScript file and take out a part of a particular line. Using the example below, I would want to remove "8:20am|8:20am" from the file, keeping everything else intact.
My JavaScript file looks like this:
var daylist = document.checkout.checkoutDay
var timelist = document.checkout.times
var times = new Array()
times[1]=["8:00am|8:00am", "8:20am|8:20am", "8:40am|8:40am", "9:00am|9:00am"]
There may be multiple lines in the Array and each with different times, so I won't know exactly where to find the string. I was thinking of maybe using str_replace() and fopen() to open the file, but without knowing what the line is going to look like ahead of time, I wouldn't know what string to replace. Any ideas?
Try this:
<?php
$file = file_get_contents( 'MY_FILE.JS' );
$search = array( '"8:20am|8:20am"' );
$replace = array( '' );
$file = str_ireplace( $search, $replace, $file );
$file = preg_replace( '/(,\s*,)/', ',', $file ); // remove 2 consecutice commas.
file_put_contents( 'MY_FILE.JS', $file );
?>
Hope it helps.
Manipulating the JavaScript file with PHP means that the JavaScript is no longer a static file and can no longer be cached by the browser, so it has to be re-downloaded every time.
It'd be better to take that times array out of the JavaScript file entirely, and make your PHP code produce an additional <script> tag in the page's header which just defines that variable. That way, the times can be generated dynamically while the rest of the JavaScript code remains static.
If you want to only replace the occurance on this specific line you may want to use preg_replace() for this:
<?php
$filename = 'yourfile.js';
$content = file_get_contents( $filename );
$search = '"8:20am|8:20am"';
$pattern = '/^(\s*times\[1\]\s*=\s*\[.*)(' .
preg_quote($search) .
',?\s*)(.*\]\s*;?)$/m';
$content = preg_replace( $pattern, '\1\3', $content );
file_put_contents( $filename, $content );
?>
Result:
var daylist = document.checkout.checkoutDay
var timelist = document.checkout.times
var times = new Array()
times[1]=["8:00am|8:00am", "8:40am|8:40am", "9:00am|9:00am"]
The regular expression is built rather complex, to allow some flexibility in matching. it allows arbitrary whitespace (which would be valid to JS as well) and removes the comma, if the value is in the middle of the list. Note that the expression also produces a valid result when there is no comma. (when you want to remove the last element from the list)
Try fopen() method and get all the file content in a php variable then you can use str_replace() for find and replace the specific string and write to same js file

How to update an ini file with 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.

Categories