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).
Related
functions/SkriptParser.php
<?php
$text = file_get_contents(basename($_SERVER['PHP_SELF']));
preg_match_all("/{(.*?)}/", $text, $matches);
var_dump($matches[0]);
echo str_replace($matches[0],"Test",$text);
?>
Is my current code, this is called from my index page which is here:
index.php
require_once 'functions/SkriptParser.php';
When i open index.php it replace the correct strings [ It'll replace any string inside {} however, it seems to be replacing <?php and I have no clue why.
Any ideas?
I'm not sure I fully understand what you are trying to do.
This line $text = file_get_contents(basename($_SERVER['PHP_SELF']));resolves to a local filename which will be the name of the script it's included in.
It won't load the page which that script would output, it will load the file without executing the code. The contents of $text will be a string containing the pure php content.
When I run your code from the command line and use "Here is a test of {your code}" as my string the output is:
{your code}<?php
require_once 'includetest.php';
print_r(basename($_SERVER['PHP_SELF']));
echo "Here's a test of Test";
If I run it from a browser and view the source I see that too, but the browser escapes the php so it isn't rendered on the page. So (for me at least), your concept kinda works. However, the fact the code isn't executed means it will never do what you intend.
Here's what I don't really understand though. In essence within index.php what you are telling your code to do is load a script which will load another copy of index.php and replace content within it.
If you want to change the behaviour of index.php then alter the code within index.php, don't generate unsuitable output and then load another script in an attempt to parse it before returning it. Just output it the way you want the first time.
Where is the content within the {} that you want to remove coming from? Why do you want/need to remove it? If you can clarify exactly what your aim is then it will be easier to suggest a solution.
What I am trying to do is write a parser for PHP that interprets whitespace instead of brackets. I can do rewriting bit and output PHP, but what I'm not sure is how best to integrate this into an application.
In an ideal world, I imagine the best thing would be to put an include at the top of the file, which in turn rewrote all the code blocks that follow it into proper PHP syntax as they are passed to the interpreter, but I am not aware that blocks of code can be passed in this way.
Another alternative is to write it as a server extension, but I would prefer not to do this, as it makes it less accessible.
Is there an easy way to architect this?
There is a way to do this with Stream Wrappers.
With that you can basically read and re-write any code that is read by PHP before it is actually interpretted. with fopen(), fwrite(), include, require, file_get_contents() etc.
So in your case you could listen for any file that is require(_once) or include(_once) and do with the code you like. You will get the entire code in a variable and with that you can simply do all sorts of replacements in strings with regex and what not.
The only downside is, is that your index.php can't make use of this method since it is not catched by any include or require. But any other code file that is included from there can be catched by the stream wrapper.
Here is an article about a plugin system that uses that method. Maybe it can be of any help.
http://phpmyweb.net/2012/04/26/write-an-awesome-plugin-system-in-php/
In there you'll also find a link to a guthub page with the source of the plugin code. In there you can basically see how to setup your Stream Wrapper class. From there on you can make up your own code as you do not have to intercept any method calls etc. like the plugin is doing.
I don't think your include idea would work as described. Since the code would be missing braces, it probably would not make it through the normal PHP parser without throwing a 500 error. So the file you want to include could never do its work.
The opposite approach might work. Write a parser script and have it read and execute your "whitespace" PHP files.
URLs might look like this: mydomain.com/my-parsing-script.php?file=script/to/parse.php
Then you'd edit .htaccess to rewrite all your URLs to make that stuff invisible to the user.
The parsing script would simply open the "whitespace" file and do some regex magic before passing the script to eval();
From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.
Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug
I would like to know how to create a php function that can be installed in php
just like the already built in functions like :
rename
copy
The main point I would like to achieve is a simple php function that can be called from ANY php page on the whole host without needing to have a php function within the php page / needing an include.
so simply I would like to create a function that will work like this :
location();
That without a given input string will output the current location of the file via echo etc
Well, there are a couple of options here. One of them is to actually extend the language by writing an extension. You'd have to muck around with the PHP source code, write it in C, and deal with the Zend Engine internally. You probably wouldn't be able to use this on a shared host and it would be quite time consuming and probably not worth it.
What I would do is put all of your functions into a separate PHP file, say helper_functions.php. Now, go into your php.ini and add the directive: auto_prepend_file = helper_functions.php. This file should be in one of the directories specified in your include_path (that's a php.ini directive too).
What this does is basically automatically put include 'helper_functions.php'; on every script. Each and every request will have these functions included, and you can use them globally.
Read more about auto_append_file.
As others have said, there's probably an easier, better way to do most things. But if you want to write an extension, try these links:
http://docstore.mik.ua/orelly/webprog/php/ch14_01.htm
http://www.tuxradar.com/practicalphp/2/3/0
So you want to extend PHP's core language to create a function called location(), written in C, which could be done in PHP by:
echo __FILE__;
Right. Have fun doing that.