Self modifying PHP script - php

I'm trying to modify a part of a PHP script structured like this barebone example
<-- part A -->
function modify_B($string)
{
some code to modify part B
}
<-- end A -->
<-- part B -->
<container>some XML</container>
<-- end B -->
<-- part C -->
<-- end C -->
I'd like to modify part B without changing the rest of the file, because A and B are the logic of the script which should not change.
Could somebody help me?
Thank you in advance for your help.

It looks like, from your example, it's just some string data XML. So load the content into a string somehow (either set a variable with standard string notation, or read it from the contents of a separate file), modify the string according to your whims, and then echo the string to the output. Then it's not a problem of being self-modifying anymore. It's just a matter of being data-driven.

Do you mean that the XML is outside of your PHP <? ?> script tags? So you want to modify the text that's about to be output by the PHP script?
If that's the case, remember that anything outside of script tags is just treated as a string, which PHP outputs as if you had written echo $string;. So just save your changed data in a string variable, and echo it.

Or if you need persistence in the changes, put "B" in a file and include or read it.

You should never write self modifying code (unless you are writing assembly) it can cause all sorts of problems, consider for example what happens if there is a bug that destroys the code in the file.
Split your data out from the code and load it with a require_once command
You can then use standard file reading and writing commands to edit the data http://www.php.net/manual/en/book.filesystem.php
... or better still since the data is XML, save the file as an XML file and use simple xml to maintain the data http://php.net/manual/en/book.simplexml.php

Related

jQuery load php file as text?

Is it possible to load a php file as text with jquery?
$('#loader').load('somefile.php', function(e){
console.log(e);
});
This always interprets/execute the php file but I'm looking for a way to only load it as text, without to resort to renaming my php file as .txt
Is it possible?
Cheers
It is not possible without making any server side modification. The web server will always interpret the php file and return the output. However does not matter what solution you find it'll be very dangereous since you'll be dumping content of your php file to public.
Possible solutions with server side modifications:
Create a PHP file that dumps the content of a file, which name is specified by a url argument
Rename the file (I know the op does not want this, just included since it's an option)
As #nicholas-young suggested, get rid of the PHP tags.
I'm not sure why you need this type of need but I want to emphasize that this might not be a good idea in most of the cases since you'll be make a working PHP file available to public. If you can explain more why you need this we might offer better solutions.
Update:
Create a dumper.php that requires authorization and call this file from the javascript side with passing the filename that you want to be dumped as a parameter (dumper.php?file=index.php)
echo file_get_contents($_GET['file']);
It is of course not possibile.
.load will make an HTTP request to yourwebsite.com/somefile.php hence you will obtain the result of your script not the PHP code inside it.
If you really need the raw code inside your javascript as a string you should output it from the php itself:
<script>
var yourCode = <?=json_encode(file_get_contents('somefile.php')) ?>;
</script>
NO! Would be a major security problem if possible. The header will not matter. If making request towards php file, it will execute prior to delivery.
Use some parameter to print out contents from file instead. But do it in the file itself.

Are there any limitations on where PHP code can go inside a file?

Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.

Does echoing javascript always work in php?

In php, if I put the following line
echo "<script type='text/javascript'>[javascript code here]</script>";
can I assume that the javascript code will be always be executed irrespective of where I put it in a php file? Assume that the php syntax is valid and the line gets executed (it is not barred by some conditions)
Edit: I have a php file where I have some javascript code and alert('ok'); but the messagebox never appears. I was wondering if the code actually got executed and the browser dismissed the messagebox as the page was changed.
No.
You might put it in a PHP file that doesn't output HTML (e.g. a PDF document or a zip file).
You might put it above a header() call and break the header
You might put it inside an if statement body so it would only be included conditionally
You might put it inside a <style> element, so it would be treated as invalid CSS
etc
PHP just outputs stuff. If you want it to output a <script> element, then you have to put it somewhere where it will be output and it somewhere where outputting it makes sense.
Yes it will be executed because it is returned to browser as html code and browser does not care where it comes from. It is also often abused in XSS attacks.
To conclude it will execute always until it is correct JS and it prints in proper place in html structure.
The code will be executed if the place in which it is inserted is valid. It will behave identically to if you had simply written the javascript code there.
For example, I'm sure the following code wouldn't work:
<ta<?php echo "<script type='text/javascript'>[javascript code here]</script>"; ?>ble>
You are messing with two pairs of shoes here. Your javascript code will not be executed anywhere on the server side (where PHP is executed). After the PHP prozessor is done and the output (including your line of javascript) is send to the client your javascript will be executed. Depending on how strict the clients browser is your <script>-element needs to be inside of the <head> or <body> Element of your HTML-page

search-and-replace on PHP code before it is executed

Is there a way to perform search and replace on PHP code before it is interpreted by PHP engine ?
Desired timeline:
PHP code is <?php echo("hello"); ?>.
Search and replace operation is hello → good bye
PHP code is now <?php echo("good bye"); ?>.
PHP engine interprets the code (output is good bye).
It is possible to manipulate the output of the PHP engine, using ob_start or even mod_substitute as an output filter of Apache. However, is it possible to manipulate the input of the PHP engine (PHP code, request, etc)?
Edit:
I'm working with thousands of PHP files and I don't want them to be modified. I would like to replace host1 with host2 in these files, since the files were copied from host1 and they have to be executed on host2. Indeed, several tests are made on the host name.
You could use a php script that opens a .php file, makes the necessary replacement, then includes that file.
Request is unusual)
Looks stupid. But if you really need it try this..
For example you need to change file test.php before execute it.
Try following steps (in index.php for example):
1) Open test.php for reading and get its content.
2) Replace everything you want.
3) Save changed text as test2.php
4) Include test2.php.
EDIT
Better thin why you need it? Try using variables.
It will help)
You should study template engines like smarty and various forms of prefilters.
Modifying code like this isn't good idea, however to answer your question... You may load original code, preprocess it and store in new file:
$contents = file_get_contents( 'original.php');
// ...
file_put_contents( 'new.php', $contents);
include( 'new.php')
But I don't see any valid use of this...
You also may possibly use eval() but every time you do that a kitty dies (no really, it's dangerous function and there's really just a few valid uses of it).

Can't pass a PHP variable to file_get_contents()

I am a newbie coder trying to build a simple web app using PHP. I am trying to send an HTML email that has a variable that will change each time it is sent. The code to initiate the email is 'email.php' and contains:
$body = file_get_contents('welcome/green2.html.php');
Within the 'green2.html.php' file, I have a variable called $highlight that needs to be populated. The $highlight variable is defined within the 'email.php' file. I had tried to simply add within the 'green2.html.php' file, however it is not being parsed. I get a blank space where the variable should be when it is output.
Also, I have done an include 'welcome/green2.html.php' within the 'email.php' file. When I echo it, the $highlight var is shown on the resulting page, but not if I echo $body.
Any help would be much appreciated!
Have you tried the str_replace function? http://php.net/manual/en/function.str-replace.php.
Add a placeholder in HTML (for instance #name# for name, #email# for email), and then use the string replace function once you've loaded the content of the file.
$bodytag = str_replace("#name#", $name, $myfile);
Loading a file via file_get_contents() will not cause it to be parsed by PHP. It will simply be loaded as a static file, regardless of whether it contains PHP code or not.
If you want it to be parsed by PHP, you would need to include or require it.
But it sounds like you're trying to write a templating system for your emails. If this is what you're doing, you'd be better off not having it as PHP code to be parsed, but rather having placeholder markers in it, and then using str_replace() or similar functions to inject variables from your main program into the string.
Hope that helps.
Use http://php.net/manual/en/function.sprintf.php put a %s in your code instead of the variable read the content and put the string into the sprintf with the variable you want to put that's it. Hope this will help.

Categories