How to find and replace a line in multiple files with PHP - php

I want to create a installer for my current project, that automatically modifies a dozens of config files.
So if the form was sent, the PHP script should look in which config file the searched option is and change it. Before you ask, I cant put the files together ;) .
A basic config line looks like this:
$config['base_url'] = 'test';.
I tried to use str_replace()but this didn't work because I don't know what is currently in the variable.
So I need a function that searches for $config['base_url'] = '%'; in multiple files and replaces it with $config['base_url'] = 'new_value'; (for example).

I realise the answer's accepted, and originally I deleted this, however, in the comments you mention the config being editable, which presumably means by other users, so you can't guarantee the spacing will match, nor that they'll use ' instead of " always, so the following is perhaps a little more forgiving
$name = 'base_url';
$value = 'new_value';
$config = '$config["base_url"] = "old_value";';
$config = preg_replace('/\[(?:\'|\")'.$name.'(?:\'|\")\]\s*=\s*(\'|\")(.*)\\1;/', "['".$name."'] = '$value';", $config);
echo '<pre>', var_dump($config), '</pre>';

You can use a regular expression like the following:
/\$config\['base_url'\] = '[a-zA-Z0-9]';/
Which you would have to adapt to each line.
A better solution, in my opinion, would be to create a template config file with lines like the following:
$config['base_url'] = '%BASE_URL%';
Where you could simply use str_replace().

Related

how to loop through a text file in php to find a specific line of text

I have made a program that lets you enter the username and password then it stores it in a text file and when i want to login i want to make it so it loops through the text file that has the usr/pass in to find if you entered your credentials in correctly. I'm not sure how to do this. please can somebody help
Example text.txt file:
$ cat text.txt
text1|answer1
text2|answer2
text3|answer3
Example code:
cat test2.php
<?php
$text="text1";
$file="text.txt";
$f = fopen($file, 'r');
while($data = fgets($f))
{
$ar_data=explode('|',$data);
if($ar_data[0]==$text) {
echo "looking for: ".$ar_data[1]."\n";
}
}
Example usage:
$ php test2.php
looking for: answer1
The text fileis not a good way for verify user credentials. You should try sql database. sqlite3 for example.
You can just hard code them in an array:
$passwords = ['someuser' => 'password'];
If you really want to store them in a file, so you can change them (for example) without editing the code, One way is to use something like this:
$passwords = ['someuser' => 'password'];
file_put_contents('passwords.php', '<?php return '.var_export($passwords,true).';');
This will create a file with something this in it (white space not withstanding):
<?php return array('someuser' => 'password');
Then when you need to import it into code you can simply use
$passwords = require 'passwords.php';
Which will put the contents of that file into that variable. Then you can check them really easily like so:
$passwords = require 'passwords.php';
if(isset($passwords[$user]) && $passwords[$user] == $password){
//do something when logged in
}
You can also modify the array and then save it:
$passwords = require 'passwords.php';
$passwords['someuser'] = $new_password;
file_put_contents('passwords.php', '<?php return '.var_export($passwords,true).';');
Of course you can even edit the passwords manually in the file. Sort of like a config file.
As I mentioned in the comments, it's better to use the DB, encryption and what not but as you said
this is only for me and someone else
As long as you don't have any third party data, and your ok with the security implications of this, then you can probably squeak by with the above.
To explain it:
Var Export converts arrays to valid PHP code, but in a string format. Then if we add the PHP open tag <?php, the return call return and the ending ; to it and save it in a PHP file, we now have a valid PHP file with dynamic passwords saved in it as an array.
When you have such a file that returns an array, you can inject that into a variable just by setting it like I showed above. Then it's a simple matter of checking to see if everything matches up.
Performance wise your offloading most of the penalty of this to saving the file, importing an array like this is very fast as is the key lookup. Much faster then iterating though a file and trying to parse the data from it.
You'll have to get the paths and filenames right and all that Jazz, but it should be pretty strait forward.

How to get all not translated texts in Smarty

Currently I am working with Smarty and been busy with translations.
I am using the config files for translation, but I cannot find a way to collect all the vars that are not in my config file. When I don't have the translation in my config file, the output is blank.
My config files look like:
register = "Registreren"
username = "Gebruikersnaam"
password = "Wachtwoord"
login = "Inloggen"
In PHP I use:
$this->smarty = new Smarty();
$this->smarty->configLoad(THEME_DIR . "/translations/nl.conf");
$this->translations = $this->smarty->getConfigVars();
echo $this->translations["username"]; // output: Gebruikersnaam
I can use in my HTML:
{#password#}
{#username#}
{#password#}
{#login#}
But when I want to output a not yet translated var like this:
{#logout#}
My result is blank.
Does anyone know how to use a default function when this occurs? Or maybe add the not found var to my config file? Or at least, show the var name instead of nothing.
There is a way that doesn't need resorting to |default for each of your variables, but it requires a little change in one of the core files.
on line 340 of smarty/sysplugins/smarty_internal_data.php
replace
return null
by
return "#$variable#";
After this, all vars not defined int he conf file will appear as #name# (i.e. this is your #password#).
If for some reason you want a variable to be empty, just define it in the conf file as
variable = ""
The only way I found was this:
{#foo#|default:'foo'}
setting a default, if the variable is empty it will display that string.
http://www.smarty.net/docsv2/en/tips.tpl

How do you get a certain portion of the Document root with PHP?

I am working a website for my friends and myself, and it needs to be a bit secure.
I have an SQL database for storing user info,
I store the variables for the database outside the public files and have
a function to retrieve them.
With this function which is called getSQL_Info($n) it takes the
line in the text file and breaks it up and puts the
variables into an array and returns array[$n].
In order to load the file with the variables I must provide the location, instead of having the path written in the function, I would like to have it so you do something like
$_SERVER['DOCUMENT_ROOT'] and use that to get the base part of the path.
Essentially, I would like to have the path "home2/(mySecretUsername)/config/file.txt"
when it gives me "home2/(mySecretUsername)/public_html/fpi".
I kinda just need a good explanation of how to take the "home2/(mySecretUsername)/" part out and add "config/file.txt".
Thanks for your time,
if I explained my question poorly please do tell me and I will add further information.
-Michael Mitchell
Would this approach work for you?
function getConfigFile() {
$components = explode('/' , $_SERVER['DOCUMENT_ROOT']);
$componentLen = count($components);
if ($componentLen < 3) {
return ''; // Something goes wrong
}
$components2 = array_slice($path, 0, $componentLen - 2);
return implode( '/' , $components2) . '/config/file.txt'
}
It's obviously platform-dependent but looks like it does the job.

Possible to use PEAR SearchReplace to replace text within a .php file?

I came across this simple pear tutorial over here: http://www.codediesel.com/php/search-replace-in-files-using-php/
include 'File/SearchReplace.php' ;
$files_to_search = array("fruits.txt") ;
$search_string = "apples";
$replace_string = "oranges";
$snr = new File_SearchReplace($search_string,
$replace_string,
$files_to_search,
'', // directorie(s) to search
false) ;
$snr->doSearch();
echo "The number of replaces done : " . $snr->getNumOccurences();
The writer uses the fruits.txt file as an example.
I would like to do a search and replace on a .php file.
Basically what I am trying to achieve would be this:
On a user interaction, index.php is opened,
$promoChange = "%VARYINGTEXT%";
is searched for and replaced with
$promoChange = "$currentYear/$currentPromotion";
The $current variables will vary, hence the need to change the words inbetween the "" only.
Does anyone have any input on how this type of task could be accomplished?
If anyone knows of any tutorials relating to this subject, that too would be greatly appreciated.
Thank you!
I do have everything else figured out, regarding the template and user interaction, I am just having trouble trying to work out how to accomplish this type of search and replace. I have an understand of how it should be done as I have made something similiar using visual basic. But I am starting to this that my answer for this would be perl? I hope that this is not so...
Okay, my problem is partly solved with this:
// Define result of Activate click
if (isset($_POST['action']) and $_POST['action'] == 'Activate')
{
include ''.$docRoot.'/includes/pear/SearchReplace.php' ;
$files = array( "$docRoot/promotions/index.php" ) ;
$snr = new File_SearchReplace( '$promoChange = "";', '$promoChange = "'.$currentYear.'/'.$currentPromotion.'";', $files) ;
$snr -> doSearch() ;
}
but how do i get it to search and replace something like $promoChange = "%VARYINGTEXT%";
It found and replaced "" with the current session values. But now that is has changed, I need it to replace and text inbetween "AND".
Any ideas anyone?
If you only need to adapt a single file, then do it manually:
$src = file_get_contents($fn = "script.php");
$src = str_replace('"%VARYINGTEXT%"', '"$currentYear/$currentPromotion"', $src);
file_put_contents($fn, $src);
str_replace is sufficient for your case.
Why on earth do you want to do something like that? Frameworks like PHP do exist solely on the base of not having to write a page for each different view of the same interaction. What's wrong with just including the PHP page you now want to change, and set the variables accordingly before calling it?
Ontopic: I don't see why what you're doing is a problem, purely technically speaking. This can be done using PHP. But really, you shouldn't.

Zend Framework : Need All parameters for application.ini

I want to know all the parameters/options which can be used in application.ini file. Is there any list available?
Please help
You can specify anything you want. For instance, I set my javascript files there:
js.jquery.filename = "/js/jquery.min.js"
js.jquery.offset = 0
js.jqueryui.filename = "/js/jquery-ui.min.js"
js.jqueryui.offset = 1
js.nestedsortable.filename = '/js/jquery.ui.nestedSortable.js'
js.nestedsortable.offset = 2
js.ckeditor.filename = "/js/ckeditor/ckeditor.js"
js.ckeditor.offset = 3
Now, whenever I need to add a javascript file, I do:
$config = Zend_Registry::get('config');
$js = $config['js'];
$this->view->headScript()->offsetSetFile($js['ckeditor']['offset'],$js['ckeditor']['filename']);
$this->view->headScript()->offsetSetFile($js['jquery']['offset'],$js['jquery']['filename']);
Like I said, you can specify any value. Anything you will be accessing often and need to be available globally can and perhaps should be there :).
During loading config in index.php you can store it in Zend_Registry and you can access them when you want.
You can also parse Zend_Config to an array and look, what is inside.
#Future King Do this:
$config = Zend_Registry::get('config');
Zend_Debug::dump($config);
That should do it. Let me know if it helps.

Categories