I would like to encode a php page which contains some php functions.
For example, I have a page named: code.php with this functions:
<?php
function data(){
echo "foo";
...
}
function storage(){
echo "storage files..";
...
}
?>
I use these functions in my other php pages and I would like to protect them by other users. How can I encode their code?
I read about base64_encode() but the examples only show how to encode a string: how can I use this solution to encode and decode my php functions?
Thank you!
If you want to stop others from seeing your PHP code you can either make it as hard as possible (via minifying, obfuscating, whatever you wish to call it) or encrypt it.
There's an answer right here on SO with a few suggestions and another I'd add is ion cube.
With encrypted code you're likely to need further changes to your web server such as an apache module. With obfuscation it will just make it harder for the other developers to read, for instance changing variables and functions names to something meaningless and hard to read.
You will inevitably need to keep a copy of your unobfuscated PHP so you can work on it in a sane manner, which may be hard if you're only developing on your server.
To use Base64 you're probably thinking of doing something like this:
eval(base64_decode('ZnVuY3Rpb24gZGF0YSgpew0KZWNobyAiZm9vIjsNCn0NCmZ1bmN0aW9uIHN0b3JhZ2UoKXsNCmVjaG8gInN0b3JhZ2UgZmlsZXMuLiI7DQp9DQokZGF0YSA9ICdkYXRhJzsNCiRzdG9yYWdlID0gJ3N0b3JhZ2UnOw=='));
What's happening here is the Base 64 string is actually valid PHP, and you first decrypt it the eval it. An example of what the decoded string might look like:
function data(){
echo "foo";
}
function storage(){
echo "storage files..";
}
$data = 'data';
$storage = 'storage';
After the above eval call you would then do something like:
// call the data function
$data();
// call the storage function
$storage();
As stated from the documentation:
PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a
function with the same name as whatever the variable evaluates to, and
will attempt to execute it.
So, calling $someVariable() will try to run a function named whatever $someVariable contains. If you set $someVariable to foo, it would try to run foo(), if you set $someVariable to sausage, it would try to run sausage() and so on.
Obviously bear in mind that you need to make sure these function variables' names aren't going to be used elsewhere.
Related
Sorry if my question is not clearly understandable, I don't know how to express well what I want to say in English.
This is not a problem with code per se, as it is working as shown, but mostly a doubt of the behaviour of PHP.
When I call a function from another php file, it seems to read the function itself i.e. function loademp(){}
however, if I access the file containing the function from an ajax, it seems to need a call to the function i.e loademp() to be in the same file.
Since I had this issue I ended having this code in order to make it work from both origins, with the call for the ajax inside an if condition, otherwise it would be called twice from the php file:
<?php
if ($_POST['runFunct']=="loademp"){ //call from ajax needs 'loademp()' to access the function;
loademp();
}
function loademp(){ //loaded from another file apparently.
try{
//PDO code
print_r(json_encode($results));
}catch(PDOException $e){
echo $e;
}
}
My other file just look like this:
require __DIR__.'loademp.php';
loademp();
Isn't there a more practical way to just use the code for both cases with no conditioning depending on the origin? Since I can't call a specific function from ajax without the use of POST variables, I guess this is the best case for it, but I would appreciate if you could point out the good practices about it.
I think your confusion here is between defining a function and executing a function.
To define a function, you write something like this:
function say_hello_world() {
echo "Hello, World!\n";
}
This doesn't cause anything to happen immediately, it just defines how to do something. In this case, it's basically like saying:
Whenever I ask you to "say hello world", output to the screen "Hello, World!\n"
To make something actually happen, you have to execute the function, which looks like this:
say_hello_world();
That's basically saying:
Do the actions I gave you for "say hello world"
In your example, your file 'loademp.php' defines a function called loademp - it says "whenever I ask you to 'loademp', here's what I want you to do". In your other file, you include that file, so the function is defined. Then, you run it with this line:
loademp();
An AJAX call is no different from any other page load, so you need to do the same thing there - first, define the function, or include the file that does; then, execute the function.
So, rather than calling loademp.php directly, you could call a PHP script like define_and_execute_loademp.php with exactly the lines you've mentioned:
require __DIR__.'loademp.php';
loademp();
Before I explain the issue, I know the risks of using eval, but there is no realy other way to do it on how my system is build, and it also is for a personal project only. (its a custom cms which when I publish it makes the physical files for me, I just made it though db so I don't need to upload files when not working remote and it is just easy).
Lets explain my issue, I have a main php file which handles all pages, all pages are stored in the db with code and all and is being executed through eval.
And the system also has a function include_db which basicly does the same as include from php normaly just from the db.
But when I access a variable defined in the first eval (main page) it can not be read out in the included eval from the db.
Weird thing is that functions can be read out though the second eval.
Any way to access variables normaly from the included eval that is being generated in the eval of the main page?
(I think it has to do because those variables are not global and its being executed in a function but I do not know a way to make every variable global :( )
Thanks in advance!
The code that is being evalled on the main page:
$skill = isset($_REQUEST['skill']) && is_string($_REQUEST['skill']) && isValidSkill($_REQUEST['skill']) ? $_REQUEST['skill'] : 'overall';
if(!isset($_REQUEST['player']))
include_db('highscore_overview');
else
include_db('highscore_player');
And inside the include of overview I dump the get_defined_vars() and that doesn't return the $skill I set before the include only the variables that are declared in the main index.php (database and such)
First of all a disclaimer: You should never ever execute code from a database. That is a big security risk. It means that whenever someone is successful in gaining access to your database (using sql-injection for example) is now also capable of executing arbitrary code in php by changing the code in your database. You really should not do that!
If you are using code from the database to implement custom (email-)templates, please consider using a templating-engine for that like twig. Most syntaxes of template-engines are built in a way that you cannot break out of them and execute arbitrary code like you could with raw php code.
That said, i now try to answer the original question (because i cannot stop you doing things you should not do anyways). In terms of variable-scope, eval behaves like a function. If you want the variables defined inside it global, you have to manually make every variable defined inside the eval global.
You can do that by append a code-snippet to every code executed in eval that takes every local (in eval defined) variable and writes it into global scope.
<?php
function include_db() {
# ... get $code from db here ...
# get's executed after code from db, globalizes all variables
$code .= ';foreach (get_defined_vars()) as $newGlobalName) {';
$code .= ' $GLOBALS[$newGlobalName] = $$newGlobalName;';
$code .= '}';
eval($code);
}
Let's say I have a PHP file some_function.php which I can run with file_get_contents('some_function.php?' . $parameters_string) (or any similar function). The parameters to this function can be given via either GET or POST HTTP method.
Instead I could include needed file and use this function within one script.
I could figure out that it could be reasonable if I need to run a separate process or I need this function to be on a separate server. But if not, is there any reasons not to do it? May be this call will be much slower? Anything else I should take into account?
I know that I will not be able to use global variables (which I assume as a bad coding style anyway).
By using file_get_contents() you will not be actually calling the function in question but will make an HTTP request passing some predefined parameters which will then be passed on the function in your code.
Using include() you could have a library of classes or functions inside that file, and call them directly as needed and as many times as needed.
EXAMPLE:
library.php
function my_function_1() { }
function my_function_2() { }
index.php
include('library.php');
my_function_1(); // call the first function
my_function_2(); // call the second function
my_function_1(); // call the first function again, just because we can
You wouldn't be able to do that through the HTTP request and even if you did hardcode your some_function.php file to do some functionality like above, you would end up with really bad code that would be hard to customize to your needs and near impossible to maintain once it gets bigger.
You cannot pass a query string via a local file_get_contents call as shown.
If you use file_get_contents on a remote HTTP URL, you will be able to use a query string, but this will be significantly slower than a local include or file_get_contents.
You can, incidentally, still include something that needs $_GET/$_POST variables:
<?php
$_GET['something'] = true;
include('something.php');
I have a function that creates an array that contains the return value from the HTML DOM method : window.document.getElementById()
function makearray1(){
var array1=[1,window.document.getElementById('divID'),['a','b'],[1,2]];
}
then I pass the array into another function
use(array1)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
and 'a' is written in the appropriate div
later I decided to put the array in a form and post it to a txt file on the server using php and:
JSON.stringify(array)
So now I use AJAX to call the data from the txt file after the rest of the page has loaded etc... and the original function used to make the array is not included at all.
so my php is basically this:
$a1='use(';
$data1 =file_get_contents("text_file.txt") ;
$a2=')';
echo $a1.$data1.$a2;
and the response text:
var n= XMLHttpRequestObject.responseText;
eval(n);
which pretty much means this:
use(text_file)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
the problem is that the array in the text file looks like this:
[1,null,['a','b'],[1,2]]
instead of:
[1,window.document.getElementById('divID'),['a','b'],[1,2]]
My question: Is there any way that I can do the equivalent of what I'm trying to do here, which is immediately replicate the return value of the HTML/DOM method in an array using AJAX/php?
To clarify: this is a simple example. I actually have a huge, multidimensional array that already has established pointers, or prefetched DOM nodes in it. Now I'm trying to replicate the array when a text version is loaded using ajax. I'm looking for a recursive approach to changing all of the null assignments with something that will immediately fetch the appropriate DOM node. Most likely I will need to do it with the response text, but was hoping I could do it with the php portion.
You're trying to stringify a reference to a javascript object in the memory of whatever computer is evaluating getElementById first, and that has no chance to represent something on the end client's computer.
Send the id instead:
function makearray1(){
array1=[1,'divID',['a','b'],[1,2]];
}
then, in the client:
function use(xxx){
window.document.getElementById(xxx[1]).innerHTML=xxx[2][0];
}
If you really want to eval it at the end, you can use this, I guess
function makearray1(){
array1=[1,"window.document.getElementById(\"divID\")",['a','b'],[1,2]];
}
I've no idea why you would want to do that though
Assuming the dom element exists in the second page, it should look something like this.
JS:
function packDomData(){
return {
"MySpecificYetBriefProperty0":1,
"DomID":"divID",
"MySpecificYetBriefProperty1":['a','b'],
"MySpecificYetBriefProperty2":[1,2]
};
}
function useDomData(domData){
document.getElementByID(domData.DomID).innerHTML=domData.MySpecificYetBriefProperty1[0];
}
PHP:
//Make sure the contents of this file is the json from packDomData. use json_encode in php or JSON.stringify in js
echo file_get_contents("text_file.txt");
var myData = JSON.parse(XMLHttpRequestObject.responseText);
useDomData(myData);
I used to code like you. Here are some tips that have helped turn my coding horror into a fun job:
Use objects with descriptive properties instead of arrays whenever you aren't actually looping through the array - I promise it will save you and others headache! "DomID" is much more flexible than 1, and if you change the order in the array, javascript gods help you that array is everywhere - including however many random text files on your server!
Also use descriptive names for functions
Always return a value from a function instead of using globals whenever possible, even where the result is then used as a nasty global. Trust me.
Never put javascript function names in an ajax call. Use JSON instead and keep the functions and other script in the javascript file where it belongs.
Mysql will save your life!!
Disclaimer - I didn't run this code but it should basically work when you get everything hooked up right.
Suppose you have access to a script which will print or echo an ID string, given a name string, i.e., something like:
http://www.example.com/script.php?name=aNameString
outputing an ID string.
I want to create a script which will allow me to retrieve anIDString, given that I already have a variable holding aNameString, i.e., something like this pseudocode:
$name="Homer Simpson";
$id='www.example.com/script.php?name=$name';
Can you help me understand how I'd do this? ... Thanks, as always!
If you are writing code on the same domain, for security reasons you might consider the include() or require() functions instead, and implementing what you need as a function in php. This way, there is no risk to your server being fed rubbish data and crashing your application.
If you need to pull data from another script do so with care, especially a server that isn't trusted. That said, you can do it with either: http://uk.php.net/curl or http://us2.php.net/manual/en/function.file-get-contents.php, the latter of which looks easier to me.
Try requiring the file, but remember, you'll need to call the function later.
<?php
$name = 'Homer Simpson';
require 'script.php';
?>
That will make the global variable $name, accessible by script.php
However, if it isn't your server, you will need to use a tool like curl to fetch the page.
In the simplest case, you can use the HTTP wrappers to get the output:
$html = file_get_contents('http://www.example.com/script.php?name=aNameString');
and them take the $html apart, unless you meant something different by "outputing an ID string", it output raw text and not html.