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

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.

Related

search plugin doesn't work on php files but only html

I'm here, because I need some help about a searching form display in php.
I've this PHP file (Is a templateMonster plugin rd-search.php) that searches some words into website that users search and types. There is a problem that I can't figure out, because words are searched in html files but not in php files. Can you tell me if it's possible make php files allowable filetypes to search in? I've tried also to add this code
$search_in = array('php','html', 'htm');
but it doesn't work. Why?
To view full code click here:enter link description here
<?php
if (!isset($_GET['s'])) {
die('You must define a search term!');
}
$highlight = true; //highlight results or not
$search_in = array('html', 'htm'); //allowable filetypes to search in
$search_dir = '..'; //starting directory
$recursive = true; //should it search recursively or not
define('SIDE_CHARS', 15);
$file_count = 0;
$search_term = mb_strtolower($_GET['s'], 'UTF-8');
if ($search_term == "?s=") {
$search_term = "";
}
?>
Here below there is a link that explains what I would like to do:
maybe I've found the solution. The problem was in the html code, I solved the issue simply adding aa specific class to a search form.
Thank to all. My best regards to all

How to find and replace a line in multiple files with 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().

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.

How to detect what page user is on with php

I need to create some if else statements depending on what page user is, I tried looking for this in php manual, but didn't find anything useful.
Basically what I want is a syntax for something like:
if (user is on a page index.php)
$message = $_GET["title"];
if $message = "hello";
$say = "Hello";
etc ....
Can anyone show how this can be done?
Try looking at _SERVER[REQUEST_URI], _SERVER[SCRIPT_NAME], _SERVER[SCRIPT_FILENAME], _SERVER[PHP_SELF], and possibly others.
you can use a session variable to track the user: every page is opened set a session variable to it's name so you can know what is the last opened page
x = str_replace('.php', '', (end(explode('/',HttpRequest::getUrl))));

How to make a zipped download with files that exist in a database?

I want to make some kind of user panel for my users - after they will update the info on the panel it will make a new row for them in the database with an original source code which i build but with the edited fields they made.
Example:
UserName: [_______]
PageID: [_______]
They fill it in and the when they press update it will automatically insert the data to a pre-made code to a new field in the table.
<?php
$username = ? (whats the best way to insert UserName textarea value in here?)
$pageid = ? (whats the best way to insert UserName textarea value in here?)
?>
Now that was the first question: whats the best way to insert UserName textarea value in here?
The Second question is how to Auto Encrypt this on insert (I don't care about the way it will be encrypted, even if it will not be IonCube encrypted it will be fine)
And the last and the most important question is how to make an automatic function that when they will press "Update" will automatically make files from the SQL field and prompt them to download the zipped files with their files (I don't want to store any of those files on my server because they may interrupt one with the other cause there may be 100 users doing this action at the same time)
Guys trust me i has been looking for this answers all over the net and didn't found a thing.. (I found EVERYTHING i need except this stuff).
Thanks for future assistance guys!
Best Regards, Rico S.
1) The best way to do it is by using some sort of formatting like
Put you template like this
$template = "whats the best way to insert %%UserName%% %%textarea%% value in here.";
And then create an array with like
$trans = array ("%%UserName%%" => $username, "%%textarea%% => $textarea);
Then use php's strtr function to convert it
$data_to_store = strtr($template, $trans);
2) You can find a lot of encryption and decryption algorithms and php classes for doing that check out PHP Classes.
3) You could try this. But i am not 100% sure if its works properly.
Use PHP's ZipArchive Directory
And then load the content's into a string
then
<?php
header('Content-Disposition: attachment; filename="downloaded.pdf"');
$zip = new ZipArchive;
$res = $zip->open('php://stdout', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('file.txt', $content_populated_from_db);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
exit;
?>
I hope this works, If it didn't try changing the flags of ZipArchive::open. And if it didn't work then also. In that case let me know, with you code and i might be able to help you. As of this point, i havn't tried it.

Categories