Evaluate PHP through AJAX - php

What I have and want to do
I have an input area.
I have a JS script what reads the input area's innerHTML and encodes it using encodeURICompontent then sends the value to evaluate.php?code=+value;
I have an evaluate.php what GET's the code's value from the URL and returns an evaluated value using eval($code) to the javascript.
And at the end it puts the xmlHttp.responseText to a div.
But I get this error when the eval is executed:
Parse error: syntax error, unexpected '"', expecting T_STRING in /Applications/MAMP/htdocs/Apps/editor/includes/exe.php(5) : eval()'d code on line 1
Evaluate.php
if(isset($_GET["code"])){
$e = $_GET["code"];
echo eval($e);
}
The value what I try to evaluate is just:
echo "Hello World!";
Then this is looks like in $_GET["code"] as:
echo \"Hello World!\";

According to PHP's documentation:
eval() returns NULL unless return is
called in the evaluated code, in which
case the value passed to return is
returned. If there is a parse error in
the evaluated code, eval() returns
FALSE and execution of the following
code continues normally. It is not
possible to catch a parse error in
eval() using set_error_handler().
So I think there may be a problem when you run echo eval($e).
P.S. It's best practice not to use double quotes in PHP unless a variable is contained within those quotes. For example, use "Hello, $name" and use 'Hello, Bob'.

Obviously you have an error in a string you are tying to evaluate. Try to output it first and see if it has semi columns and things like that.
But you should never (!) evaluate code you get from URL! Never-never, anyone can send "exec('rm -rf /')".

I feel terrible answering this. In your PHP settings, magic_quotes_gpc might be enabled which "corrupts" your incoming data by escaping it.
In order to get it working, you might want to add a little more insecurity to your undertaking by disabling magic quotes.
If that doesn't fix it, debug your input by following Silver Light's suggestions.

Related

PHP functions: passing variables by reference (and if not possible) by value

I am trying to build an "escape" function (as an exercise). The objective of this function is to transform "dangerous" values into safe values to be inserted in a database. The content of this function is not important.
function escape(&$value){
//some code
return $value;
}
Here's the problem: I want to make this function very handy to use, therefore it should be able to support 2 possible scenarios:
1) returning a safe value:
$safe_val = escape($unsafe_val);
2) changing a variable "by reference":
escape($value);
At the moment, my function does its job, however...if I pass something like:
$safe_val = escape(php_native_change_string_to_something($value));
PHP gets angry and says:
Notice: Only variables should be passed by reference
How can I make PHP accept that if something can't be passed by reference it does not matter and it should just ignore the error and continue the execution?
PHP is complaining because the value being passed into escape by escape(php_native_change_string_to_something($value)) is a temporary value (rvalue). The argument has no permanent memory address so it does not make sense to modify the value.
However, despite this not making sense, PHP will still do what you want. You are receiving a notice, not an error. Your code should still produce the output you are expecting. This short program models your setup:
<?php
function escape (&$s) {
return $s;
}
$s = 'TEXT TO ESCAPE';
$new_s = escape( strtolower( $s ) );
echo "$s\n";
echo "$new_s\n";
and produces the following results:
s: TEXT TO ESCAPE
new_s: text to escape
If you would like to get rid of the notice you will need to use the error control operator (#), #escape(php_native_change_string_to_something($value)).
Despite this being something that will work in PHP I would suggest avoiding this type of usage as it will decrease code readability and is not suggested by PHP (as the notice indicates).

PHP Array - Missing Entry

Can anyone tell me, if there is an error in the following code, please?
eval ("\$typeselectbit = \"".$cmstpl->get("admin_selectbitdefault")."\";");
$result = $cmsdb->query("SELECT * FROM cms".$n."_type WHERE deleted = '0' ORDER BY typename ASC");
while ($type = $cmsdb->fetch_array($result))
{
$typeid = $type['typeid'];
$typename = $type['typename'];
eval("\$typeselectbit .= \"".$cmstpl->get(ifelse($GPC['typeid'] == $typeid, "typeselectbit2", "typeselectbit"))."\";");
}
It doesn't output the first entry from the array. But maybe the error is somewhere else.
At the moment, I'm not sure, where this problem is coming from.
What do you think? Does it look correct to you?
And if not, what do I have to fix and how exactly should it look like?
Or do I have to look somewhere else in the script?
Any specific hints, which could help to find the reason?
Thank you for your help! :)
The last line in your code eval("\$typeselectbit .= \"".$cmstpl->get(ifelse($GPC['typeid'] == $typeid, "typeselectbit2", "typeselectbit"))."\";"); has a parse error. ifelse is not valid PHP syntax (unless that is a function you have declared previously). It could also be any other number of errors occurring inside of the eval construct.
According to the manual
If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().
It's not clear why you chose to use eval at all here, but one of the down sides, among others, is that you typically can't easily debug these kinds of errors inside of eval. If you ran this code outside of eval you'd immediately see the parse error.

PHP - evaluating param

I have following code:
<?php
$param = $_GET['param'];
echo $param;
?>
when I use it like:
mysite.com/test.php?param=2+2
or
mysite.com/test.php?param="2+2"
it prints
2 2
not
4
I tried also eval - neither worked
+ is encoded as a space in query strings. To have an actual addition sign in your string, you should use %2B.
However, it should be noted this will not perform the actual addition. I do not believe it is possible to perform actual addition inside the query string.
Now. I would like to stress to avoid using eval as if it's your answer, you're asking the wrong question. It's a very dangerous piece of work. It can create more problems than it's worth, as per the manual specifications on this function:
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
So, everything that you wish to pass into eval should be screened against a very.. Very strict criteria, stripping out other function calls and other possible malicious calls & ensure that 100% that what you are passing into eval is exactly as you need it. No more, no less.
A very basic scenario for your problem would be:
if (!isset($_GET['Param'])){
$Append = urlencode("2+2");
header("Location: index.php?Param=".$Append);
}
$Code_To_Eval = '$Result = '.$_GET['Param'].';';
eval($Code_To_Eval);
echo $Result;
The first lines 1 through to 4 are only showing how to correctly pass a character such a plus symbol, the other lines of code are working with the data string. & as #andreiP stated:
Unless I'm not mistaking the "+" is used for URL encoding, so it would
be translated to a %, which further translates to a white space.
That's why you're getting 2 2
This is correct. It explains why you are getting your current output & please note using:
echo urldecode($_GET['Param']);
after encoding it will bring you back to your original output to which you want to avoid.
I would highly suggest looking into an alternative before using what i've posted

handling php eval syntax error for mathematic equations

suppose I do this in php:
eval("\$answer=1--1;");
The expression 1--1 will lead to a syntax error in eval, my question is how do I detect the error and handle it gracefully? ie: catch error in eval and then print out a helpful message. Right now, it just spits out "Parse error: syntax error, unexpected T_DEC". Unfortunately, the php manual states that it is not possible to catch parse errors with the set_error_handler() function.
This is for a simple school assignment and they have suggested using "eval()".
As the assignment is trivial, perhaps there is no need to worry about these rare cases.
Prepend the string with something like echo 'd41d8cd98f00b204e9800998ecf8427e';.
Turn on output buffering.
eval
Get contents of the output buffer and delete it.
Test whether the contents start with 'd41d8cd98f00b204e9800998ecf8427e'.
Alternatively, use the Parsekit.
There are not a single reason to use eval for math equations.
As there are thousands math parsers around. Safe and maintainable.
By pre-pending # symbol to eval to suppress the error output, and then by checking error_get_last():
$test = #eval($str);
if (error_get_last())
var_dump(error_get_last());
Then, parse the PHP token referenced in the error message ('message' value, or T_DEC in your case) against the list: http://php.net/manual/en/tokens.php
However, certain parse errors may fail your entire script, such as calling undefined functions. And, because you suppressed the error output, the failure won't appear in your logs. Basically: avoid eval for anything other than an amusing toy to pass the time.
Edit: I was going by the assumption "\$answer=1--1;" is not really the value you want to check (just too obvious), but just a test example of what kinds of strings you might be passing to eval. If it is really, you should just fix it right there. But if you want to pass and check any string at all in eval, then the above will help.

What is the meaning of 'var_export($_REQUEST, true)' in PHP

Can anybody please tell me what this means in PHP?
var_export($_REQUEST, true)
It converts $_REQUEST to a string, which would evaluate to the array, then returns it.
See the documentation of var_export.
Actually, your code tries to execute var_export(Array, true) in a shell as you have backticks around it (even though you most likely just accidentally put them when posting the line as code here on SO).
But without the backticks, your code exports $_REQUEST to PHP code which could be used to re-create an array with the same data.
Edit: Aww, now they have been edited away.
Try
var_export($_REQUEST['true'])
Returns true to the client, if the operation was successful.
Otherwise you can send any message.

Categories