473,607 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

before eval(), how can one test a string to see if it is valid PHP code?

I have a string which I want to send to eval(). How can I test it
ahead of time to make sure it is valid code? I don't want to send it
to eval and get parse errors. I want to do something like this:

$valid = checkPHP($strin g);
if ($valid) {
eval($string);
} else {
$resultsObject->addToErrorResu lts("We wanted to send our
template to eval(), but the PHP it contained was invalid.");
}
Is there anything like checkPHP()?
Jul 17 '05 #1
12 8167
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:
I have a string which I want to send to eval(). How can I test it
ahead of time to make sure it is valid code? I don't want to send it
to eval and get parse errors. I want to do something like this:

$valid = checkPHP($strin g);
if ($valid) {
eval($string);
} else {
$resultsObject->addToErrorResu lts("We wanted to send our
template to eval(), but the PHP it contained was invalid.");
}
Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?

--
Andy Hassall <an**@andyh.co. uk> / Space: disk usage analysis tool
<http://www.andyh.co.uk > / <http://www.andyhsoftwa re.co.uk/space>
Jul 17 '05 #2
Andy Hassall wrote:
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:

Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?


Right!
But I prefer another name for the function :)

<?php
function is_validPHP($co de) {
$code = escapeshellarg( '<?php ' . $code . ' ?>');

$lint = `echo $code | php -l`; // command-line PHP

// maybe there are other messages for good code?
return (preg_match('/No syntax errors detected in -/', $lint));
}

# usage example
$code1 = '$xx=date("Y-m-d"); return $xx;';
if (is_validPHP($c ode1)) echo "code1 is valid PHP code\n";
else echo "code1 is invalid\n";

$code2 = '$xx=date("Y-m-d") return $xx;'; // no semicolon
if (is_validPHP($c ode2)) echo "code2 is valid PHP code\n";
else echo "code2 is invalid\n";

############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>
Output is:
code1 is valid PHP code
code2 is invalid
code3 is valid PHP code
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #3
"Pedro Graca" <he****@hotpop. com> wrote in message
news:c2******** *****@ID-203069.news.uni-berlin.de...
############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>


However, please feel free to try it at work :)

And if you do, I also have a bridge for sale if you are interested.

--
Mike Bradley
http://www.gzentools.com -- free online php tools
Jul 17 '05 #4
CountScubula wrote:
"Pedro Graca" <he****@hotpop. com> wrote in message
news:c2******** *****@ID-203069.news.uni-berlin.de...
############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>
However, please feel free to try it at work :)
Well ... I did try that at home.

And if you do, I also have a bridge for sale if you are interested.
I think I'm entitled to a discount for the Brooklyn bridge :)
--
Mike Bradley
http://www.gzentools.com -- free online php tools


Hey Mike! Your sig is broken.
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #5
Hi Lawrence,

I think there really ought to be a check() function that parses but does not
evaluate PHP code. But AFAIK there isn't.

Since the eval command is executing in the same environment as the rest of
the PHP code, when it returns an error and dies it affects the whole
environment. So, the workaround solution is to execute a sub-process to
evaluate the code and return the result to the main process. This can be
done using exec and command-line PHP:

<?PHP
$string1 = "php -r 'pint ('foo');'";
$string2 = "php -r 'print ('foo');'";
$result1 = exec($string1);
$result2 = exec($string2);
print $string1." returned: ".$result1. "<br />\n";
print $string2." returned: ".$result2. "<br />\n";
?>

From here you can probably create your checkPHP() function by grepping the
output for words like "Fatal error." Better would be if you know the
expected output to grep for that. Or maybe you can check the command-line
PHP exit status. Use the return_var for this.

Either way by spawning a sub-process to evaluate your code you are saved
from this affecting the main environment and therefore well on your way to a
solution.

Good luck.

Cheers,
Robert

On 3/8/04 3:31 PM, in article
da************* *************@p osting.google.c om, "lawrence"
<lk******@geoci ties.com> wrote:
I have a string which I want to send to eval(). How can I test it
ahead of time to make sure it is valid code? I don't want to send it
to eval and get parse errors. I want to do something like this:

$valid = checkPHP($strin g);
if ($valid) {
eval($string);
} else {
$resultsObject->addToErrorResu lts("We wanted to send our
template to eval(), but the PHP it contained was invalid.");
}
Is there anything like checkPHP()?


Jul 17 '05 #6
I posted earlier but my messages are not getting through via Comcast.
Weird...

A parse error in eval() doesn't cause the running script to die, so
all you have to do is stick a @ in front of the call:

$php_errormsg = false;
$track_errors = ini_set('track_ errors', 1);
@eval("How much wood would a woodchuck chuck if a wood chuck could
chuck
wood?");
ini_set('track_ errors', $track_errors);

echo "Error: $php_errormsg";

A fatal error (e.g. call to undefined function) would still kill the
script,
however.
Pedro Graca <he****@hotpop. com> wrote in message news:<c2******* ******@ID-203069.news.uni-berlin.de>...
Andy Hassall wrote:
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:

Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?


Right!
But I prefer another name for the function :)

<?php
function is_validPHP($co de) {
$code = escapeshellarg( '<?php ' . $code . ' ?>');

$lint = `echo $code | php -l`; // command-line PHP

// maybe there are other messages for good code?
return (preg_match('/No syntax errors detected in -/', $lint));
}

# usage example
$code1 = '$xx=date("Y-m-d"); return $xx;';
if (is_validPHP($c ode1)) echo "code1 is valid PHP code\n";
else echo "code1 is invalid\n";

$code2 = '$xx=date("Y-m-d") return $xx;'; // no semicolon
if (is_validPHP($c ode2)) echo "code2 is valid PHP code\n";
else echo "code2 is invalid\n";

############### ############### ###
#### WARNING ####
#### DO NOT TRY THIS AT HOME ####
############### ############### ###

$code3 = '$dummy = `rm -rf ..`;'; // VALID CODE!!!!!!!
if (is_validPHP($c ode3)) echo "code3 is valid PHP code\n";
else echo "code3 is invalid\n";
?>
Output is:
code1 is valid PHP code
code2 is invalid
code3 is valid PHP code

Jul 17 '05 #7
Pedro Graca <he****@hotpop. com> wrote in message news:<c2******* ******@ID-203069.news.uni-berlin.de>...
Andy Hassall wrote:
On 8 Mar 2004 15:31:16 -0800, lk******@geocit ies.com (lawrence) wrote:
Is there anything like checkPHP()?


Pipe it through the command-line version of PHP with the -l flag?


Right!
But I prefer another name for the function :)

<?php
function is_validPHP($co de) {
$code = escapeshellarg( '<?php ' . $code . ' ?>');

$lint = `echo $code | php -l`; // command-line PHP

// maybe there are other messages for good code?
return (preg_match('/No syntax errors detected in -/', $lint));
}


Thanks much. Sadly, it doesn't work for my purposes. I'm trying to
offer end-users the option of editing the template for the admin
control panel that runs their websites, but I'm pretty sure some of
them will screw it up and destroy the control panel. Even experienced
PHP programmers can make a simple gramatical mistake. So I'd love to
take the template and test it for mistakes and maybe do a roll back to
the previous version, before their changes, if there are errors.

I found that I can send ordinary HTML pages to eval() so long as I put
"?>" at the beginning. This lets eval() know that it is breaking out
of PHP and into normal HTML. This is how the system currently works on
the sites that are run with this software (www.alexmarshall.org, for
instance).

I'm trying to run it through here:

function renderControlPa nelTemplate() {
$builtInControP anelTemplates =
$GLOBALS["builtInControP anelTemplates"];
$defaultTemplat e = $builtInControP anelTemplates["misty"];
$end = "?";
$end .= ">";
$defaultTemplat e = $end.$defaultTe mplate;
if ($valid = is_valid($defau ltTemplate)) {
eval($defaultTe mplate);
} else {
echo "<h1>We tried to load the template for the control panel but it
was full of errors in its PHP.";
}
}

Would all be well if I change this line:
$code = escapeshellarg( '<?php ' . $code . ' ?>');
to this:

$code = escapeshellarg( ' $code ');

Jul 17 '05 #8
lawrence wrote:
Pedro Graca <he****@hotpop. com> wrote in message news:<c2******* ******@ID-203069.news.uni-berlin.de>... Would all be well if I change this line:
$code = escapeshellarg( '<?php ' . $code . ' ?>');


to this:

$code = escapeshellarg( ' $code ');


I think yes.

"eval($stri ng)" start in PHP mode
"`php -l $string`" starts out of PHP mode

You just have to make sure you get into the right mode for whatever
instruction you're going to call.
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #9
On 3/9/04 5:00 PM, in article
da************* *************@p osting.google.c om, "lawrence"
<lk******@geoci ties.com> wrote:
Pedro Graca <he****@hotpop. com> wrote in message
news:<c2******* ******@ID-203069.news.uni-berlin.de>...
I'm trying to
offer end-users the option of editing the template for the admin
control panel that runs their websites, but I'm pretty sure some of
them will screw it up and destroy the control panel.


First of all, never allow end users the option of executing arbitrary code
on your system. Ever. There are a lot of things far worse a PHP error
message that can happen.

That said, I wrote the function for you. Since the php command line function
returns a non-zero (i.e. not 'clean') exit status for every error type
(fatal, parse, warning) that would also appear on your site via default PHP
error reporting, you can write the function this way:

<?PHP

function checkPHP($strin g) {
$string = escapeshellcmd( $string);
exec("php -r \"$string\"",$o utput,$exit);
if($exit==0) return TRUE;
else return FALSE;
}

/* tests */
$test = array ("print ('foo');",
"print (\"foo\");",
"pint ('foo');",
"print ('foo);",
"print ('foo','bar');"
);

for($i=0;$i<siz eof($test);$i++ ) {
print $test[$i];
if(checkPHP($te st[$i])) {
print " is ok.<br />\n";
} else {
print " not ok.<br />\n";
}
}

/* browser output:

print ('foo'); is ok.
print ("foo"); is ok.
pint ('foo'); not ok. <- fatal
print ('foo); not ok. <- parse
print ('foo','bar'); not ok. <- warning
*/
?>

Cheers,
Robert
--
Robert Peake | Peake Professional Consulting
Ro****@PeakePro .com | http://www.peakepro.com/

Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3057
by: lkrubner | last post by:
We are probably lucky that PHP doesn't allow this, but I'm curious about what the argument is against allowing this? Why did the inventors of PHP keep this from working? This same thing, using eval to create a class defintion, works in Javascript, demonstrating, perhaps, that Javascript is very flexible and you can do awful things with it. Anyway, the following code prints out "class does not exist". <?php
12
4043
by: Kamilche | last post by:
I was looking for a way to speed up detecting invalid characters in my TCP string, and thought of yet another use for the translate function! If you were to 'translate out' the bad characters, and compare string lengths afterwards, you would know whether or not the line contained invalid characters. The new method is more than 10x faster than the standard 'if char in string' test! So - here's the code plus sample timings: ''' Translate...
9
8456
by: HikksNotAtHome | last post by:
This is a very simplified example of an Intranet application. But, is there an easier (or more efficient) way of getting the decimal equivalent of a fraction? The actual function gets the select values, this one is a simplified version where its passed. function checkIt(selVal){ valueInDec1 = eval(selVal); //do some calculations here with valueInDec1 }
3
6302
by: McKirahan | last post by:
I said I wouldn't use "eval()" anymore but I need help to do it. Below is some stripped-down code (4 lines; watch for word-wrap) extracted from USGA.COM that preloads images: main_nav_home_F1 = new Image(153,21); main_nav_home_F1.src = "images/main_nav_home.gif"; main_nav_home_F2 = new Image(153,21); main_nav_home_F2.src = "images/main_nav_home_F2.gif"; main_nav_about_F1 = new Image(153,21); main_nav_about_F1.src =
9
1855
by: Mike | last post by:
After reading much on the evils of eval, I have a question using my own personal use of the function... We have a reports system that will generate reports based on a number of parameters available on a blotter at the top of our report system. Each report could (and does) use a combination of some (but not all) of these 15 parameters. Each report also has a series of precalculations that need to be run before the report can execute.
12
3425
by: knocte | last post by:
Hello. I have always thought that the eval() function was very flexible and useful. If I use it, I can define functions at runtime!! However, I have found a case where eval() does not work properly. It works, for example, when invoking functions (alert('hello')), but not for defining functions. The case occurs when retrieving the javascript code with
15
3651
by: manstey | last post by:
Hi, I have a text file called a.txt: # comments I read it using this:
12
3773
by: Logos | last post by:
Yes, eval is a tool of the devil and I'll burn for using it. However, in this instance it's quite handy and I'm quite lazy. So, here's a weird one, and I'm wondering if anyone has a workaround. I am pulling data off a server via AJAX, and some of that data has non-English characters in it. The data is in the form of a json: {"exitCode":1,"className":"clientRecords" ,"strAccountId":"100" ,"strName":"Dr. Gary A. Martin"
7
5053
by: Darko | last post by:
Hello, I have this particular problem with eval() when using Microsoft Internet Explorer, when trying to define an event handler. This is the code: function BigObject() { this.items = new Array(); this.values = new Array();
0
7987
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8472
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8130
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8324
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6805
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6000
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5471
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4015
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2464
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.